new principles

function Person(age){
    this.age= age;
    console.log(this);
    return {age:age};//返回对象
}
var person1 = new Person(20);

the new operator to do what?

  1. Create a new object
  2. The scope of a function assigned to the new object (this is actually producing a new context)
  3. The execution code function (add properties, methods for the new object)
  4. When the expedition returned in step 3 the value returned, no return value or return value of a non-object, the new object is created is returned, otherwise the return value will be returned as a new object. (That will return an object back, this step can be obtained from the following conclusions Code)
new Person(20) = { // new 实际执行情况

    var obj = {};

    obj.__proto__ = Person.prototype;

    var result = Person.call(obj,20);

    return typeof result === 'object'? result : obj;
}  // Person{age: 20}

Therefore, the above var person1 = new Person (20); when executed, create a new object obj {}, then the object points _proto_ prototype object of prototype Person

At this point the prototype chain for the new object obj. Proto > Person.prototype-> Object.prototype-> null, obj method on the property inherited Person.prototype, realized JavaScript inheritance
Here Insert Picture Description

So this points to the new object, then the age of the property given person1, finally returned object with belonging to the age of 20. Instead of using new, but the execution result of the function returns. var person2 = Person (18);

function Person(age){
    this.age= age;
    console.log(this);
    return age; // 如果去掉这里,console.log(person2);为undefined
}
var person1 = new Person(20);
var person2 = Person(18);
 
console.log(person1);
console.log(person2);

After modifying the code, do not use the new instantiated only function execution result is obtained, it was used to instantiate new a new object is obtained. Although the function returns a value instead of the object, but based on the implementation of the new fourth step, the return value is non-object, still inside the new Person object will return.

Summary:
By the new operator, we can create an instance of the object of the original object, and this instance object inherits the properties and methods of the original object, so the meaning of existence is that it implements the new javascript in succession, not just instantiate an object.

Published 149 original articles · won praise 5 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_26327971/article/details/105047388