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

JavaScript 深入之 new 的模拟实现 #25

Open
wengjq opened this issue Feb 25, 2018 · 0 comments
Open

JavaScript 深入之 new 的模拟实现 #25

wengjq opened this issue Feb 25, 2018 · 0 comments

Comments

@wengjq
Copy link
Owner

wengjq commented Feb 25, 2018

mqyqingfeng/Blog#13

function new() {
    var obj = new Object(),

    var Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    var ret = Constructor.apply(obj, arguments);

    return typeof ret === 'object' ? ret : obj;
};

function new() {
    var obj = new Object();
    Constructor = [].shift.call(arguments);
        // 寄生继承
    var F = function () {};
    F.prototype = Constructor.prototype;
    obj = new F();
    
    var ret = Constructor.apply(obj, arguments);

    return typeof ret === 'object' ? ret : obj;
};

发生看如下四步操作:

  • 创建一个新的对象,这个对象的类型是 object 。
  • 该对象的 prototype 设置为构造器的 prototype 属性,即 this.prototype = Foo.prototype (伪代码)
  • 执行构造器函数。
  • 如果构造器函数有返回值,则以该对象作为返回值。若没有 return 或 return 了基本类型,则将上述的新对象作为返回值。
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