是否有相当于PHP的'父'与javascript原型继承?

时间:2011-04-01 01:49:28

标签: javascript

我正在使用protypal继承,我想在基类上调用重写方法。在PHP中,我可以使用parent :: functionName来完成此操作。这可能是使用JavaScript protypal继承吗?

考虑以下示例:

var A = function(){

    this.doSomething = function(){
         console.log('doSomething in A');
    };

};


var B = function() {

   this.doSomething = function(){
         //I would like to call A.doSomething()
         //I tried this.prototype.doSomething() and A.doSomething.call(this), but neither works
         console.log('doSomething in B');
    };

};

B.prototype = new A();


var test = new B();
test.doSomething();

我在控制台中寻找的输出是:
在B中做一些事 做一件事

2 个答案:

答案 0 :(得分:2)

我在以下小提琴中定义了代码:http://jsfiddle.net/JAAulde/psdym/2/

最好的方法是.call()或.apply()B的内部方法:

//Inside of B.doSomething
A.prototype.doSomething.call( this, arg1, arg2 );

或者,简单地通过一次性进入B.doSomething()的所有参数

//Inside of B.doSomething
A.prototype.doSomething.apply( this, arguments );

一本很棒的书(由我的一位朋友撰写),用于了解JS中各种继承模式http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X

答案 1 :(得分:0)

来自我自己的最佳实践,最好创建

var parent = ...;

创建对象时,如果实际需要引用父对象 - 这并不像人们期望的那样多。然后根据需要使用。

我个人认为“对象”一词在引用javascript时会产生误导,因为

object == function == closure

本质上为对象提供工具而不限制正式的对象/继承约束。从好的方面来说,它是一种非常流畅,可变的语言;在缺点方面,您需要在需要时填写自己缺失的部分。