[英]What are the difference between adding a property to instance or adding to prototypeproperty?
I have the following class:我有以下 class:
class PersonCl {
constructor(fullName, age) {
this.fullName = fullName;
this.age= age;
}
// Instance methods
// Methods will be added to .prototype property
calcAge() {
console.log(2037 - this.birthYear);
}
greet() {
console.log(`Hey ${this.fullName}`);
}
}
now i have lets say two object that were created from the constructor:现在我可以说两个从构造函数创建的 object:
const Joe = new PersonCl('Joe',23);
const Larisa = new PersonCl('Larisa',41);
i'm asking what is the difference between:我在问有什么区别:
1.adding the property species into constructor and set it exactly where we set the fullName and age. 1.将属性种类添加到构造函数中,并将其设置在我们设置全名和年龄的位置。
or adding the following line outside the class declaration:或在 class 声明之外添加以下行:
PersonCl.prototype.species = "Male"; PersonCl.prototype.species = "男性";
The "species" property placed on the prototype object will be visible on all instances in most (but not all situations).在大多数情况下(但不是所有情况),原型 object 上的“物种”属性将在所有实例上可见。 As soon as your code makes a change to "species":
一旦您的代码对“物种”进行了更改:
someInstance.species = "tiger";
then that instance will have a local property "species", and the value of "species" on other instances will not change.那么该实例将具有本地属性“species”,并且其他实例上的“species”值不会改变。
Clearly, when the property is directly added to instances in the constructor, all instances will be similarly initialized (given your sample code) but thereafter changes can still be made on an instance-by-instance basis.显然,当属性直接添加到构造函数中的实例时,所有实例都将被类似地初始化(给定您的示例代码),但此后仍然可以逐个实例进行更改。 The key point is that updating a property value on an object always makes a local, "own" property of that object and does not affect the prototype.
关键是更新 object 上的属性值总是会生成该 object 的本地“自己”属性,并且不会影响原型。
Some methods intended to help work with object properties as a collection, like Object.keys()
, only involve "own" properties, which means properties directly associated with an object and not inherited properties.一些旨在帮助将 object 属性作为集合使用的方法,例如
Object.keys()
,仅涉及“自己的”属性,这意味着与 object 直接关联的属性而不是继承的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.