Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Метод Object.create (https://javascript.ru/forum/events/67065-metod-object-create.html)

Mess4me 26.01.2017 15:30

Метод 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;
}

destus 26.01.2017 17:25

Mess4me,
Цитата:

Cat.prototype = Animal.prototype;

так ты получаешь ссылку на прототип Animal, и добавленные методы в Cat.prototype, будут доступны и в Animal.prototype
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 :(

Mess4me 26.01.2017 21:33

А как так получается ,что у объекта Animal доступна функция meow , если я нигде не ссылался на Cat.prototype?

destus 27.01.2017 06:38

Mess4me,
возможно, это то, что ты ищешь Объекты: передача по ссылке


Часовой пояс GMT +3, время: 08:31.