JavaScript 原型构造函数只调用一次
JavaScript prototype constructor called only once
我的 javascript class 原型构造函数只为我的所有实例调用一次,而不是每个实例调用一次。将唯一超级实例链接到子实例的正确方法是什么 class?
使用下面的代码,我希望得到输出,所有 uniqueId 都是唯一的:
Org {uniqueId: 4}
Org {uniqueId: 5}
Org {uniqueId: 6}
Sub {uniqueSubId: 1, uniqueId: 1}
Sub {uniqueSubId: 2, uniqueId: 2}
Sub {uniqueSubId: 3, uniqueId: 3}
然而,实际输出是,所有 Sub 都有 uniqueId 1:
Org {uniqueId: 2}
Org {uniqueId: 3}
Org {uniqueId: 4}
Sub {uniqueSubId: 1, uniqueId: 1}
Sub {uniqueSubId: 2, uniqueId: 1}
Sub {uniqueSubId: 3, uniqueId: 1}
代码:
var OrgCounter = 0;
var Org = function() {
this.uniqueId = ++OrgCounter;
}
var SubCounter = 0;
var Sub = function() {
this.uniqueSubId = ++SubCounter;
}
Sub.prototype = new Org;
console.log(new Org());
console.log(new Org());
console.log(new Org());
console.log(new Sub());
console.log(new Sub());
console.log(new Sub());
您不应该使用 Parent 实例设置 Child.prototype;特别是如果您不重新使用 Parent 构造函数(Parent.call(this,...) in Child)。全部在这里详细解释:
和这里:
您应该使用 Object.create 设置子原型:
Sub.prototype = Object.create(Org.prototype);
我的 javascript class 原型构造函数只为我的所有实例调用一次,而不是每个实例调用一次。将唯一超级实例链接到子实例的正确方法是什么 class?
使用下面的代码,我希望得到输出,所有 uniqueId 都是唯一的:
Org {uniqueId: 4}
Org {uniqueId: 5}
Org {uniqueId: 6}
Sub {uniqueSubId: 1, uniqueId: 1}
Sub {uniqueSubId: 2, uniqueId: 2}
Sub {uniqueSubId: 3, uniqueId: 3}
然而,实际输出是,所有 Sub 都有 uniqueId 1:
Org {uniqueId: 2}
Org {uniqueId: 3}
Org {uniqueId: 4}
Sub {uniqueSubId: 1, uniqueId: 1}
Sub {uniqueSubId: 2, uniqueId: 1}
Sub {uniqueSubId: 3, uniqueId: 1}
代码: var OrgCounter = 0;
var Org = function() {
this.uniqueId = ++OrgCounter;
}
var SubCounter = 0;
var Sub = function() {
this.uniqueSubId = ++SubCounter;
}
Sub.prototype = new Org;
console.log(new Org());
console.log(new Org());
console.log(new Org());
console.log(new Sub());
console.log(new Sub());
console.log(new Sub());
您不应该使用 Parent 实例设置 Child.prototype;特别是如果您不重新使用 Parent 构造函数(Parent.call(this,...) in Child)。全部在这里详细解释:
和这里:
您应该使用 Object.create 设置子原型:
Sub.prototype = Object.create(Org.prototype);