Interview js - handwritten code to realize the function of the new operator

We have to figure out the new operator in the end to do some what?

1. Create a new object

2. The scope of the constructor assigns a new object (and therefore this point to the new object)

3. Run the code constructor (add the new object property)

4. Return the new object

The above shows the new operator in the end to do some something, we step by step to achieve this, it is not to achieve a new operator functions.

Person first define a constructor as follows:

function Person(name) {
    this.name = name;
}
Person.prototype.sayName = function () {
    console.log(this.name);
}

Then create a new simulation function operator functions as follows:

function the Person (name) {
     the this .name = name; 
} 
Person.prototype.sayName = function () { 
    the console.log ( the this .name); 
} 

function createPerson () {
     // . 1 creates a new object 
    var O = { };
     // 2 acquires the constructor in order to achieve binding scope 
    var _constructor = [] .shift.call (arguments);
     // . 3 due to the nature of the inaccessible interior new object instance is created by the operation of [[the Prototype] ] (some browsers which is __proto__) 
    // points to the prototype object constructor, so to achieve this manually bind. 
    .__ proto__ = O _constructor.prototype;
     // bind 4. Use apply scope of this change point
_constructor.apply(o, arguments); return o; } var person1 = createPerson(Person, 'ydb'); person1.sayName();

This way is realized the function of the new operator.

In fact, the above code can also be written like this:

function the Person (name) {
     the this .name = name; 
} 
Person.prototype.sayName = function () { 
    the console.log ( the this .name); 
} 

function createPerson () {
     // . 1 acquires the constructor in order to achieve scope binding 
    var _constructor = [] .shift.call (arguments);
     // 2 creates an object 
    var O = the Object.create (_constructor.prototype);
     // Since inaccessible property inside the object instance is created by the new operator [ [prototype]] (some browsers which is __proto__) 
    // points to the prototype object's constructor. 
    // The Object.create () method creates a new object, using the existing object to provide __proto__ newly created object. //4. Binding scope 
    _constructor.apply (O, arguments);
     return O; 
} 
var PERSON1 = createPerson (the Person, 'YDB' ); 
person1.sayName ();

Can create an object with no properties Object.create, as follows:

var o = Object.create(null);

 

Guess you like

Origin www.cnblogs.com/jsydb/p/12240426.html