【发布时间】:2015-08-19 04:34:30
【问题描述】:
在这里,我创建了一个函数,该函数最终将用作其他克隆的构造函数。除了创建的属性arguments, caller, length, name, __proto__(link to Function.protoype) 之外,还创建了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 原型属性上添加属性。一个接一个。
但如果我之后这样做:
Clonetrooper.prototype = {
name: null
hasDroid: null
};
我已经覆盖了指向 Clonetrooper's 构造函数的链接,将其替换为链接到 Object.prototype 的新 Object。
所以我的问题是,最后一个语法确实覆盖了您的 prototype 属性?
所以可能应该仔细计划一个object 以避免这种情况发生。
【问题讨论】:
-
嗯,你没有错。你还有什么想问的吗?
-
@Qantas94Heavy 更好的是: 问题是什么? (唯一的问题是标题和输出 cmets。)
-
基本上!!!!起初我看不到当你使用这种语法时,你基本上是在创建一个新对象,而不是创建一个速记来加快属性创建。
-
如果问题是要理解为什么会这样,那么一个好的开始就是阅读 Ch。 5 个You Don't Know JS: this & Object Prototypes.
-
@AntonioOrtiz 如果你不知道原型,试试这个:
({}).__proto__。将{}替换为您希望的任何值。 (可能不适用于 IE)或Object.getPrototypeOf()(文档:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
标签: javascript prototype javascript-objects