The new principle and implementation

new process

// new运算的过程
/**
 * 1、创建一个空对象;
 * 2、该空对象的原型指向构造函数(链接原型):将构造函数的 prototype 赋值给对象的 __proto__属性;
 * 3、绑定 this:将对象作为构造函数的 this 传进去,并执行该构造函数;
 * 4、返回新对象:如果构造函数返回的是一个对象,则返回该对象;否则(若没有返回值或者返回基本类型),返回第一步中新创建的对象;
 */
var Person = function(name) {
    this.name = name
    console.log('name is ', this.name)
}
Person.prototype.getName = function() {
    return this.name
}
var objectFactory = function() {
    // 1、创建一个空对象
    var obj = new Object()
    console.log('before shift arguments = ',arguments)
    // 获取构造函数Person
    Constructor = [].shift.call(arguments)
    //因为arguments是类数组,并不是真正的数组,所以不能直接调用数组的shift方法,但是可以通过call调用。
    console.log('after shift arguments = ', arguments)
    console.log(`Constructor = ${Constructor}`)
    // 2、该空对象的原型指向构造函数: 将构造函数的prototype 赋值给空对象的 __proto__属性;
    obj.__proto__ = Constructor.prototype
    // 3、将空对象作为构造函数的this传进去,并执行该构造函数
    var ret = Constructor.apply(obj, arguments)
    // 4、返回新对象:如果构造函数返回的是一个对象,则返回该对象;否则(若没有返回值或者返回基本类型),返回第一步中新创建的对象;
    return typeof ret == 'object' ? ret : obj
}
var a = objectFactory(Person, 'wyh')
console.log('执行后的name = ', a.name)

The fourth step to achieve new explanation:

Constructor returns values ​​are the following three cases:

  • 1, returns an object
  • 2, no return, that returnundefined
  • 3, return to undefinedthe basic type except

Case 1 : Returns an object

function Car(color, name) {
    this.color = color;
    return {
        name: name
    }
}

var car = new Car("black", "BMW");
car.color;
// undefined

car.name;
// "BMW"

Examples carcan only have access to the returned object attributes .

Case 2 : No return, that returnundefined

function Car(color, name) {
    this.color = color;
}

var car = new Car("black", "BMW");
car.color;
// black

car.name;
// undefined

Examples carcan only have access to the constructor properties , and an opposite situation.

Case 3 : return undefinedbasic types other than

function Car(color, name) {
    this.color = color;
    return "new car";
}

var car = new Car("black", "BMW");
car.color;
// black

car.name;
// undefined

Examples carcan only have access to the constructor properties , and an opposite situation, the result is equivalent to no return value.

Therefore, the value returned by next need to determine is not an object, if the object is an object that is returned, otherwise returns the newly created objobject.

Guess you like

Origin www.cnblogs.com/w-yh/p/12008171.html
Recommended