Skip to content

Instantly share code, notes, and snippets.

@SirSerje
Last active October 21, 2021 06:16
Show Gist options
  • Save SirSerje/80480d4881d42c0c354af4b1f329b75b to your computer and use it in GitHub Desktop.
Save SirSerje/80480d4881d42c0c354af4b1f329b75b to your computer and use it in GitHub Desktop.
1 - prototype inheritance
Array.prototype.odd = function () {
return this.filter(i => i%2 === 1)
}
console.log([1,2,3,4,5,6].odd())
const someCup = {
space: 300,
color: 'red',
material: 'glass',
handle: true
};
function Cup(space, color, material) {
// this = {}
this.space = space;
this.color = color || 'black';
this.material = material || 'glass';
//return this
}
Cup.prototype.isHot = function () {
return false
}
const greenCup = new Cup(300, 'green')
const redGlassCup = new Cup(200, 'red', 'glass')
console.log(redGlassCup.isHot())
//es6
class CoffeeMachine {
constructor(model, source = 'powder', power) {
//this = {} //explicitly - неявно
this.name = model;
this.source = source
this.power = power
//return this
};
turnOn() {
if (this.power>=0) {
console.log('turned on')
return true
}
}
}
class AmericanCoffeeMachine extends CoffeeMachine {
constructor(model, source = 'powder') {
// //this = {} //explicitly - неявно
super(model, source) // вызываем код с 3й строки
this.power = 110;
// //return this
};
turnOn() {
super.turnOn()
console.log('some')
}
}
const nespresso = new CoffeeMachine('Nespress Cappucchino', 'capsules', 220);
// console.log(nespresso)
// nespresso.turnOn()
const americanNespresso = new AmericanCoffeeMachine('American', 'powder', 110)
console.log(americanNespresso.turnOn())
console.log(americanNespresso.__proto__ === AmericanCoffeeMachine.prototype)
console.log(americanNespresso.__proto__.__proto__ === CoffeeMachine.prototype)
console.log(americanNespresso.__proto__.__proto__.__proto__ === Object.prototype)
//old es5
function CoffeeMachineOld(model, source) {
this.name = model;
this.source = source;
}
const oldMachine = new CoffeeMachineOld('Nespress Cappucchino', 'capsules');
console.log(oldMachine)
let animalActions = {
sleep: function () {
console.log('sleep')
return 'sleep'
}
}
let animal = {
eat: true
}
animal.__proto__ = animalActions
let bear = {
hasClaws: true
}
let eagle = {
canFly: true,
transfer: function () {
console.log('на пути в теплые страны')
},
render: function () {
}
}
eagle.__proto__ = animal
// bear.__proto__ = animal
// bear.__proto__ = animalActions
// console.log(bear.eat)
// eagle.__proto__ = animal
// eagle.transfer()
eagle.sleep()
console.log(eagle.sleep())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment