Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new操作符 #98

Open
unproductive-wanyicheng opened this issue Aug 15, 2021 · 0 comments
Open

new操作符 #98

unproductive-wanyicheng opened this issue Aug 15, 2021 · 0 comments

Comments

@unproductive-wanyicheng
Copy link
Owner

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant