【问题标题】:Passing a prototype to Object.Create()将原型传递给 Object.Create()
【发布时间】:2020-07-27 19:36:30
【问题描述】:

编辑:孩子是一个对象。对不起,我对此很陌生

我对 Object.create() 的工作方式感到困惑。我知道你传入的任何东西都会返回一个以该参数作为原型的新对象。我的老师将此列为经典继承的示例:

child.prototype=Object.create(parent.prototype)

下面的示例没有完成什么(在继承方面):

child = Object.create(parent)

【问题讨论】:

  • prototypes 确实适用于constructors 的函数,但它们本身就是对象。这些根本不是一回事。
  • 你没有提到child是什么,child是一个函数还是一个普通对象有很大的不同..

标签: javascript inheritance prototype


【解决方案1】:

test1 中,我们可以看到Constructor1.prototype 没有使用Object.createConstructor2.prototype 继承。在test2 中,您可以看到发生了prototype 继承,因为通过调用new 创建的Object 具有来自Constructor1 的属性。 test3 表明 prototype 这样的分配根本不起作用。

function Constructor1(test = 'see'){
  this.test = test; this.yeah = 7; 
  this.fun = function(q){
    this.test = q;
    return this;
  }
}
function Constructor2(q = true){
  this.noInheritedProps = q;
}
Constructor2.prototype = Object.create(Constructor1.prototype);
const test1 = new Constructor2, obj1 = new Constructor1('with argument'), test2 = Object.create(obj1);
console.log(test1); console.log(test2); Constructor2.prototype = Constructor1.prototype;
const test3 = new Constructor2('once again true');
console.log(test3);

【讨论】:

    【解决方案2】:

    让我们先解释一下你问题的第二部分

    根据您的回答,child 是对象而不是函数

    child = Object.create(parent)

    这会做什么?

    1- 这将创建一个名为 child 的对象 强文本 2-它将使用对象parent作为对象child的原型__proto__,所以如果parent有一个名为lastName : Thomson的属性,那么现在child 可以通过其__proto__ 属性访问此属性 parent 对象中的任何方法/函数也是如此,child 对象现在可以访问它。

    现在到第一部分:

    child.prototype = Object.create(parent.prototype)

    这会做什么?

    1- 这假设在某处已经创建了一个名为 child 的对象 在脚本中

    2- 它将一个名为 prototype 的属性分配给 child 对象,因此现在您可以编写类似 child.prototype 的内容并获得一些结果

    3- Object.create(parent.prototype) 运行转换/使您刚刚创建的属性child.prototype 成为一个对象,然后使该对象的__proto__ 等于 parent.prototype 应该是一个对象,我的意思是 parent.prototype 需要是一个对象才能工作。


    注意:

    对象实例(常规对象,例如 let obj = {}; )没有 .prototype 属性,但它们会自动继承名为 __porto__ 的东西 来自他们的构造函数,不幸的是也被称为原型

    另一方面,构造函数/函数有一个 .prototype 属性,你可以 像任何其他属性一样操作,这个.prototype 属性稍后会传递给该构造函数/函数的实例

    这是一个非常有趣的话题,如果您想了解更多关于 javascript 的信息,我鼓励您深入研究。

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 2012-06-29
      • 2013-02-15
      • 1970-01-01
      • 2018-06-18
      • 2016-07-10
      • 2021-06-08
      • 1970-01-01
      相关资源
      最近更新 更多