简体   繁体   English

如何在javascript中实现基本成员?

[英]How do I implement base members in javascript?

I want a base class to share its member variables with the child class, how do I do that? 我希望基类与子类共享其成员变量,该怎么做?

Example code: 示例代码:

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);

As you can see there, the base class has its own implementation of objects and that is separate from the childs version. 如您所见,基类具有自己的对象实现,并且与子版本分开。 How do I fix that? 我该如何解决?

fiddle: http://jsfiddle.net/8094g8ta/ 小提琴: http//jsfiddle.net/8094g8ta/

What you need to do is have the child constructor call the parent constructor so that the parent initialization runs for each child: 您需要做的是让子构造函数调用父构造函数,以便为每个子实例运行父初始化:

var child = function () {
    base.call(this);

    this.objects.push(2, 3, 4);
};

Once you have this, it doesn't make sense to use new base to create the child prototype since it's redundant, and in fact, calling constructors to create prototypes is now an outdated practice. 一旦有了这个,使用new base来创建子原型就没有意义了,因为它是多余的,实际上,调用构造函数来创建原型现在已经过时了。 Instead, use Object.create() : 而是使用Object.create()

// child inherits from base
child.prototype = Object.create(base.prototype);

Putting it all together: 放在一起:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM