开发者

Javascript subclassing and createElement

function A() { this.myProp = document.createElement("div"); }

function B(id) {
    this.myProp.id = id;
    document.body.appendChild(this.myProp); }

B.prototype = new A();

window.onload = function() {
    new B(开发者_运维百科"hello");
    new B("goodbye"); }

What happens here is that I end up with one div with id "goodbye". What I would like is two divs with the specified ids.

I have been able to fix this problem by creating a method of "A" which creates the element.

How could I fix it without using the method?


You have to call the constructor A() when creating a new B():

function A() {
    this.myProp = document.createElement("div");
}

function B(id) {
    A.call(this); // !!!
    this.myProp.id = id;
    document.body.appendChild(this.myProp);
}

If you want B instances to inherit from A.prototype, don't set B.prototype to an A instance, but use Object.create() - or a custom implementation for legacy browsers - to avoid a constructor invocation:

var clone = Object.create || (function() {
    function Dummy() {}
    return function(obj) {
        Dummy.prototype = obj;
        return new Dummy;
    };
})();

B.prototype = clone(A.prototype);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜