【问题标题】:Difference between Object.create & new keyword in javaScriptjavaScript中Object.create和new关键字的区别
【发布时间】:2019-01-30 12:57:45
【问题描述】:

为什么输出出现在一种情况下而不是另一种情况下?他们俩的 proto 中都有一个变量,但在一种情况下我变得不确定。

【问题讨论】:

标签: javascript prototypal-inheritance proto


【解决方案1】:

当您键入 p.constructor.prototype.a 时,JavaScript 会检查对象本身中的属性 constructor,但它没有。当这种情况发生时,它会通过__proto__ 遍历原型链。这里的问题是对象p 及其原型没有属性constructor。这是由使用Object.create() 引起的。它与new 之间的区别已经在Understanding the difference between Object.create() and new SomeFunction() 中进行了描述,@adiga 在您的帖子下评论:)

【讨论】:

    【解决方案2】:

    这很简单。

    new a is Object.create(a.prototype)

    虽然 Object.create(a) 与 Object.create(a.prototype) 不同。 new 运行构造函数代码,而 object 不运行构造函数。

    参见以下示例:

    function a(){
        this.b = 'xyz';
    };
    
    a.prototype.c = 'test';
    var x = new a();
    var y = Object.create(a);
    
    //Using New Keyword
    console.log(x); //Output is object
    console.log(x.b); //Output is xyz.
    console.log(x.c); //Output is test.
    
    //Using Object.create()
    console.log(y); //Output is function
    console.log(y.b); //Output is undefined
    console.log(y.c); //Output is undefined
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-08
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 2016-05-14
      • 2018-10-09
      相关资源
      最近更新 更多