在这里,我创建了一个函数,该函数最终将用作其他克隆的构造函数。除了创建的属性arguments、caller、length、name、__proto__(链接到Function.protoype)
之外,还创建了prototype
属性。此属性指向一个对象,该对象将作为原型(prototype)分配给使用 new
关键字调用此函数时创建的实例。
function Clonetrooper(ID, rank, yearsOfService, type){
if (!(this instanceof Clonetrooper)){
return new Clonetrooper(ID, rank, yearsOfService, type);
}
this.ID = ID;
this.rank = rank;
this.yearsOfService = yearsOfService;
this.type = type;
}
所以当我这样做时:
Clonetrooper.prototype.hasUtilityBelt = true;
Clonetrooper.prototype.hasLightSaber = false;
我正在 Clonetrooper
原型(prototype)属性上添加属性。一一。
但是如果我之后这样做:
Clonetrooper.prototype = {
name: null
hasDroid: null
};
我已经覆盖了 Clonetrooper's
构造函数的链接,将其替换为链接到 Object.prototype 的新 Object
。
所以我的问题是,最后一个语法确实覆盖了您的 prototype
属性?
因此,人们可能应该仔细规划一个对象
以避免这种情况发生。
最佳答案
是的,我们必须小心。在大多数情况下,我们应该通过以下两种方式之一扩展现有原型(prototype):
Clonetrooper.prototype.foo = ...
或(例如使用 jQuery)
$.extend(Clonetrooper.prototype, {
bar: ...,
baz: ...
})
关于javascript - 这是正确的(JavaScript 原型(prototype)属性)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30645973/