Skip to content

new操作符 #98

Open
Open
@unproductive-wanyicheng

Description

new 做了如下事情:
// (1)首先创建了一个新的空对象
// (2)设置原型,将对象的原型设置为函数的 prototype 对象。
// (3)让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
// (4)判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。

对着这几个步骤几乎可以直接写出代码了:

function newOperation() {
    // 不直接写参数 接受任意长度的参数 构造函数 + 参数列表...
    let newObject = null,
    constructor = Array.prototype.shift.call(arguments),
    result = null;

    // 参数判断
    if (typeof constructor !== "function") {
        console.error("type error");
        return;
    }

    // 新建一个空对象,对象的原型为构造函数的 prototype 对象
    newObject = Object.create(constructor.prototype);

    // 将 this 指向新建对象,并执行函数
    result = constructor.apply(newObject, arguments);

    // 判断返回对象
    let flag =
        result && (typeof result === "object" || typeof result === "function");

    // 判断返回结果
    return flag ? result : newObject;
}

// 测试一下

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

var child1 = new Parent('wan1');
child1.sayName(); // wan1

var child2 = newOperation(Parent, 'wan2');
child2.sayName(); // wan2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions