Code Example 1: __proto__ — link to prototype
❓ Что выведут rabbit.eats и rabbit.__proto__ === animal?
var animal = { eats: true };
var rabbit = { jumps: true };
rabbit.__proto__ = animal;
console.log(rabbit.eats);
console.log(rabbit.__proto__ === animal);
Code Example 2: prototype — property of functions
❓ Что выведет bunny.__proto__ === Rabbit.prototype? Почему?
function Rabbit(name) {
this.name = name;
}
Rabbit.prototype.jump = function() {
console.log(this.name + ' прыгает');
};
var bunny = new Rabbit('Кролик');
console.log(bunny.__proto__ === Rabbit.prototype);
bunny.jump();
Code Example 3: Key connection
❓ Какова связь между bunny.__proto__, Rabbit.prototype и Rabbit.prototype.constructor?
function Rabbit() {}
var bunny = new Rabbit();
console.log(bunny.__proto__ === Rabbit.prototype);
console.log(Rabbit.prototype.constructor === Rabbit);
console.log(bunny.constructor === Rabbit);
Code Example 4: Difference in practice
❓ Что выведет cat.prototype? В чём разница между cat.__proto__ и Animal.prototype?
function Animal() {}
Animal.prototype.eats = true;
var cat = new Animal();
console.log(cat.__proto__ === Animal.prototype);
console.log(Animal.prototype);
console.log(cat.prototype);
Code Example 5: Prototype of function itself
❓ Чему равен Example.__proto__? Почему Example.prototype !== Example.__proto__?
function Example() {}
console.log(Example.__proto__ === Function.prototype);
console.log(Example.prototype !== Example.__proto__);
Code Example 6: Object and Function
❓ Что выведут все console.log? Почему Function.__proto__ === Function.prototype?
console.log(typeof Object);
console.log(Object.prototype);
console.log(Object.__proto__ === Function.prototype);
console.log(Function.__proto__ === Function.prototype);
console.log(Function.prototype.__proto__ === Object.prototype);
Code Example 7: constructor
❓ Как свойство constructor связано с prototype? Можно ли создать новый объект через user.constructor?
function User() {}
console.log(User.prototype.constructor === User);
var user = new User();
console.log(user.constructor === User);
var user2 = new user.constructor();
console.log(user2 instanceof User);
Code Example 8: Changes in prototype affect objects
❓ Почему cat.speak() работает, хотя метод speak был добавлен после создания cat?
function Animal() {}
var cat = new Animal();
Animal.prototype.speak = function() {
console.log('Мяу');
};
cat.speak();
Code Example 9: Confusing prototype and __proto__
❓ Что выведут dog.prototype и dog.__proto__? В чём ошибка при обращении к dog.prototype?
function Dog() {}
var dog = new Dog();
console.log(dog.prototype);
console.log(dog.__proto__);
Code Example 10: prototype is NOT function's own prototype
❓ Что выведет Cat.__proto__ === Cat.prototype? Объясните разницу между этими двумя свойствами.
function Cat() {}
console.log(Cat.__proto__ === Cat.prototype);