Метод Object.create
Добрый день!
Есть скрипт
function Animal(name){
console.log('Animal',this);
this.name = name;
}
Animal.prototype.getName = function () {
console.log('getName',this);
return this.name;
};
function Cat(name){
console.log('Cat',this);
Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.meow = function(){
console.log('meow',this);
return 'Cat '+ this.getName() +' is saying meow';
};
var cat = new Cat('garfield');
console.log(cat.getName() === 'garfield'); // true
console.log(cat.meow() === 'Cat garfield is saying meow'); // true
Чем чем будет отличаться логига , если строку 15 заменить на: Cat.prototype = Animal.prototype; Если посмотреть на эмуляцию метода Object.create он возвращает объект :
function inherit(proto) {
function F() {}
F.prototype = proto;
var object = new F;
return object;
}
|
Mess4me,
Цитата:
function Animal(name){
console.log('Animal',this);
this.name = name;
}
Animal.prototype.getName = function () {
console.log('getName',this);
return this.name;
};
function Cat(name){
console.log('Cat',this);
Animal.call(this, name);
}
Cat.prototype = Animal.prototype;
Cat.prototype.meow = function(){
console.log('meow',this);
return 'Cat '+ this.getName() +' is saying meow';
};
var cat = new Cat('garfield');
var animal = new Animal('dog');
console.log(cat.getName() === 'garfield'); // true
console.log(cat.meow() === 'Cat garfield is saying meow'); // true
console.log(animal.meow() === 'Cat dog is saying meow');// UPS!! Dog say meow :(
|
А как так получается ,что у объекта Animal доступна функция meow , если я нигде не ссылался на Cat.prototype?
|
Mess4me,
возможно, это то, что ты ищешь Объекты: передача по ссылке |
| Часовой пояс GMT +3, время: 17:13. |