我希望基类与子类共享其成员变量,我该怎么做?
示例代码:
var register = function(f){
setTimeout(function(){
f('123');
}, 5000);
};
var base = function(){
var self = this;
this.objects = [];
this.events = {
token : register(function(data){
self.objects.push(data); //THIS WONT MODIFY THE child VERSION OF objects, how do I do that??
})
};
};
var child = function(){
var self = this;
this.objects = [2, 3, 4];
};
// child inherits from base
child.prototype = new base;
child.prototype.constructor = child;
child.prototype.parent = base.prototype;
var d = new child();
var e = new child();
setTimeout(function(){
$('body').html(d.objects.join(",") + " " + e.objects.join(","));
//prints out: "2,3,4 2,3,4" i want: "2,3,4,123 2,3,4,123"
}, 6000);
正如您所看到的,基类具有自己的对象实现,并且与子版本分开。我该如何解决这个问题?
答案 0 :(得分:2)
您需要做的是让子构造函数调用父构造函数,以便为每个子进程运行父级初始化:
var child = function () {
base.call(this);
this.objects.push(2, 3, 4);
};
一旦你有了这个,使用new base
创建子原型是没有意义的,因为它是多余的,事实上,调用构造函数来创建原型现在已经过时了。相反,请使用Object.create()
:
// child inherits from base
child.prototype = Object.create(base.prototype);
全部放在一起:
var register = function(f) {
setTimeout(function() {
f('123');
}, 5000);
};
var base = function() {
var self = this;
this.objects = [];
this.events = {
token: register(function(data) {
self.objects.push(data);
})
};
};
var child = function() {
base.call(this);
this.objects.push(2, 3, 4);
};
// child inherits from base
child.prototype = Object.create(base.prototype);
child.prototype.constructor = child;
child.prototype.parent = base.prototype;
var d = new child();
var e = new child();
setTimeout(function() {
$('body').html(d.objects.join(",") + " " + e.objects.join(","));
}, 6000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>