【问题标题】:Declaring properties in Prototype vs. Constructor function? Pros and Cons? [duplicate]在原型与构造函数中声明属性?优点和缺点? [复制]
【发布时间】:2019-01-12 02:54:22
【问题描述】:

我很难理解为什么要在构造函数类或其原型对象上定义属性。

这里是我对原型的理解 - 在原型中声明属性(而不是链接的父对象)可以节省性能,因为每个子对象都不会拥有自己的父属性副本。

问题:但我认为您不能从非原始类型复制值,即函数对象只能传递引用......并且只能从原始类型复制?

**这是否意味着如果我继承父类的方法,如下所示,我正在复制对方法的引用或实际复制? **

function Parent() {
   this.name = "jeff";
}

var child = new Parent();
console.log(child.name); /// is copied from parent or the reference is copied?? 

在下面的例子中,我引用了原型……对吗?

Parent.prototype.age = 9;
child.age // I looks at the parent class, then reference to prototype.age.

****问题2:**如果我可以更改特定对象的prototype.age,那么我实际上是复制了该值,对吗?那么重点是什么,即**

child.age = 10; // changed the value for THIS object

【问题讨论】:

  • 抱歉,错过了新关键字。

标签: javascript inheritance prototype prototypal-inheritance


【解决方案1】:

你搞混了一些事情。这在尝试从 OO 角度理解 javascript 时很常见,因为它不太适合。也许这会有所帮助:

这只是一个函数(当使用new 调用时)返回一个对象:

function Parent() {
   // create a new object and call it this
   this.name = "jeff";
}

它返回的对象每次都是新创建的,并且该对象是 this 所引用的对象。所以每次你运行它时,它都会创建一个对象,给该对象一个name 参数设置为jeff 并返回。是否使用动态属性更容易查看:

function Parent() {
    console.log("creating a new object and a new value")
    this.value = Math.floor(Math.random()* 100000);
 }
 
 var child1 = new Parent();
 console.log("child1: ", child1)

 var child2 = new Parent();
 console.log("child2: ", child2)

值不是继承的,它只是在调用函数时分配给对象。 Parent 只是一个函数。

像所有函数一样 Parent 有一个 prototype 属性。当它使用new 创建一个对象时,它将将该对象链接到它的prototype。如果您尝试在返回的对象上查找属性但找不到它,则 javascript 将查找父原型。当您分配 child.age = 10 现在孩子有自己的年龄属性。它不再需要查看原型。如果它没有自己的属性,它只会在原型上查找属性。

function Parent() {
    this.name = "Jeff"
}

Parent.prototype.age = 9
 
var child = new Parent();

// child has no age prop so it looks on the prototype:
console.log(child.age)
console.log("Has age:", child.hasOwnProperty('age'))

child.age = 20
// now child has its own age property. It doens't look at the prototype
console.log("Has age:", child.hasOwnProperty('age'))
console.log(child.age)

【讨论】:

  • 当你说:值不是继承的,它只是分配的......你的意思是复制或引用还是别的什么?
  • @Shaz 否。在函数体中,它被 分配 字符串文字:this.name = "Jeff"
  • 我没有问,那么子对象是否被分配 this.name 值?对?没有复制。未参考。分配?
  • 正确。函数Parent() 创建一个新对象并赋予它自己的属性name 然后返回该对象。
  • 我有点明白。但是分配的定义非常松散。这是什么意思?引擎是否创建了一个新的内存空间并分配了值,即复制。或者指针指向父引用。哪一个?
猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 2016-07-02
  • 2012-04-04
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2010-10-07
  • 2016-01-07
相关资源
最近更新 更多