In most interviews, the interviewer has laid out the prototype chain and then asks you what the new keywords did. And to pave the way again for the next succession issue! In this article, we will talk about the new! We usually see it somewhere, when we create an instance, new is followed by a constructor, which is creating an instance of that constructor.
First let’s create a constructor and see what new does:
function Person() {
this.name = 'Jack';
this.age = 'and';
}
Person.prototype.eat = function() {
console.log('duck'); } var person = new Person(); console.log(person.name); //Jack console.log(person.age); // 29 person.eat(); / / the roast duckCopy the code
As we can see from the above, new keyword mainly does the following things:
- Creates a new object,
- By referring the new object’s __proto__ function to the constructor’s prototype, the new object can access the properties on the constructor’s prototype
- Pointing this to the change, to the new object, allows access to the properties inside the constructor
- Return a new object
Let’s simulate the new function:
function MyNew() {
let obj = new Object();
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
Constructor.apply(obj, arguments);
return obj;
}
Copy the code
Let’s verify that this method is correct:
function Person() {
this.name = 'Jack';
this.age = 'and';
}
Person.prototype.eat = function() {
console.log('duck'); } var person = MyNew(Person); console.log(person.name); //Jack console.log(person.age); // 29 person.eat(); / / the roast duckCopy the code
After all, the constructor is a function. If the constructor has a return value, what would be the result of new?
// Return the basic data typefunction Person() {
this.name = 'Jack';
this.age = 'and';
return 1;
}
Person.prototype.eat = function() {
console.log('duck'); } var person = new Person(); console.log(person.name); //Jack console.log(person.age); // 29 person.eat(); // Return the objectfunction Person() {
this.name = 'Jack';
this.age = 'and';
return {
sex: 'nan',
like: 'nv'
};
}
Person.prototype.eat = function() {
console.log('duck');
}
var person = new Person();
console.log(person.name); //undefined
console.log(person.age); // undefined
console.log(person.sex); //Jack
console.log(person.like); // 29
person.eat(); // Uncaught TypeError: person.eat is not a function
Copy the code
When the constructor returns a primitive datatype, the result is the same as if it did not return a value, but when the return value is an object, the object is actually returned, and all properties defined before return are invalidated, as well as properties defined on the stereotype. Based on this feature, the MyNew function that was previously written is upgraded.
function MyNew() {
let obj = new Object();
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
let res = Constructor.apply(obj, arguments);
return typeof res === 'object' ? res : obj;
}Copy the code