Code Example 1: Four ways to create objects
❓ Какие четыре способа создания объектов продемонстрированы в этом коде?
// 1. Литерал объекта
var obj1 = { name: 'Иван' };
// 2. Конструктор Object
var obj2 = new Object();
obj2.name = 'Мария';
// 3. Функция-конструктор
function Person(name) {
this.name = name;
}
var obj3 = new Person('Алексей');
// 4. Object.create()
var obj4 = Object.create(Object.prototype);
obj4.name = 'Елена';
Code Example 2: Object literal
❓ Что выведет вызов user.greet()? Почему this внутри метода ссылается на user?
var empty = {};
var user = {
name: 'Иван',
age: 25,
greet: function() {
console.log('Привет, ' + this.name);
}
};
user.greet();
var company = {
name: 'IT Corp',
address: {
city: 'Москва',
street: 'Тверская'
}
};
Code Example 3: Constructor function
❓ Что происходит при вызове new User('Иван', 25)? Что вернёт user1 instanceof User?
function User(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Привет, я ' + this.name);
};
}
var user1 = new User('Иван', 25);
var user2 = new User('Мария', 30);
console.log(user1.name);
console.log(user2.name);
console.log(user1 instanceof User);
console.log(user1.constructor === User);
Code Example 4: Operator new
❓ Какие шаги выполняет оператор new при вызове конструктора?
function User(name) {
this.name = name;
}
var user = new User('Иван');
Code Example 5: With new vs Without new
❓ Чем отличается вызов new User('Иван') от вызова User('Иван') без new? Что произойдёт во втором случае?
Version A — с new:
function User(name) {
this.name = name;
}
var user = new User('Иван');
console.log(user.name);
console.log(user instanceof User);
Version B — без new:
function User(name) {
this.name = name;
}
var user = User('Иван');
console.log(user);
console.log(window.name);
Code Example 6: Object.create()
❓ Как Object.create() создаёт наследование? Что выведет dog.speak()?
var obj1 = Object.create(Object.prototype);
var obj2 = Object.create(null);
console.log(obj2.toString);
var animal = {
speak: function() {
console.log(this.name + ' говорит');
}
};
var dog = Object.create(animal);
dog.name = 'Шарик';
dog.speak();
Code Example 7: Object.create(null)
❓ В чём разница между Object.create(null) и {}? Почему dict['__proto__'] ведёт себя по-разному в двух случаях?
var dict = Object.create(null);
console.log(dict.toString);
console.log(dict.hasOwnProperty);
dict['__proto__'] = 'значение';
console.log(dict['__proto__']);
var regular = {};
regular['__proto__'] = 'значение';
console.log(regular['__proto__']);
Code Example 8: Protection from forgotten new
❓ Как этот паттерн защищает от вызова конструктора без new?
function User(name) {
if (!(this instanceof User)) {
return new User(name);
}
this.name = name;
}
var user1 = new User('Иван');
var user2 = User('Мария');
Code Example 9: Return from constructor
❓ Что выведут obj.a и obj.b? Что произойдёт, если конструктор вернёт примитив?
function Strange() {
this.a = 1;
return { b: 2 };
}
var obj = new Strange();
console.log(obj.a);
console.log(obj.b);
function Normal() {
this.a = 1;
return 42;
}
var obj2 = new Normal();
console.log(obj2.a);