2014-01-12 188 views
0

我创建一个框架以简化面向对象与原型编码。但我在思考JavaScript中的继承问题。JavaScript的扩展对象和原型

默认情况下,延长一个对象,我们写:

var B = function() { /*...*/ } ; 
B.prototype = new A() ; 

但对于一个构造函数需要一个参数?

var A = function(args) { 
    if (!args) throw "Arguments required." ; 
} ; 

或许一个构造函数也可以被instancied之前执行不必要的东西。

什么你会建议更换默认继承行为? (我想到了所有成员存储所有“类”的复制,同时继承或混入。)

回答

3

如果你想从一个原型继承,而不调用构造函数,你可以使用Object.create()做这样的事情:

var B = function() { /*...*/ }; 

B.prototype = Object.create(A.prototype); 
B.prototype.constructor = B; 

在上面,Object.create(A.prototype)将返回一个新的对象,其原型是由A.prototype给出,它这样做,而无需调用A()。第二条线是有那么你可以看一下constructor属性对B的任何情况下,它会重新指向B()

有一点要注意的是,Object.create()是比较新的,所以你可能需要为旧版浏览器的一个填充工具。你可以在这里找到一个,更多的信息一起:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

1

我通常使用一个defclass效用函数中的JavaScript来定义“类”:

function defclass(base, body) { 
    var uber = base.prototype; 
    var prototype = Object.create(uber); 
    var constructor = (body.call(prototype, uber), prototype.constructor); 
    constructor.prototype = prototype; 
    return constructor; 
} 

然后我用它如下:

var A = defclass(Object, function() { 
    this.constructor: function (arg1, arg2) { 
     this.arg1 = arg1; 
     this.arg2 = arg2; 
    } 

    this.log = function (which) { 
     console.log(which ? this.arg1 : this.arg2); 
    }; 
}); 

继承是死的简单:

var B = defclass(A, function (uber) { 
    this.constructor = function (arg1, arg2, arg3) { 
     uber.constructor.call(this, arg1, arg2); 
     this.arg3 = arg3; 
    }; 

    this.log = function (which) { 
     uber.log.call(this, which); 
     console.log(this.arg3); 
    }; 
}); 

正如你可以当我们延伸的“类”看到我们使用Object.create。这是继承的新方式。使用new是陈旧的。在B构造我们通过参数的A使用uber.constructor.call构造。

如果你喜欢这种模式,那么你应该看看augment库。

+0

确实有趣的图书馆。但是我不喜欢用'this.prop = value;'来定义属性和方法。 – Tot