是否有与JavaScript原型继承等效的PHP“父级"? [英] Is there an equivalent of PHP's 'parent' with javascript prototypal inheritance?

查看:46
本文介绍了是否有与JavaScript原型继承等效的PHP“父级"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用原型继承,我想在基类上调用重写的方法.在PHP中,我可以使用parent :: functionName来做到这一点.使用JavaScript原型继承是否有可能?

I'm using protypal inheritance and I would like to call an overridden method on the base class. In PHP I could do this using parent::functionName. Is this possible using JavaScript protypal inheritance?

请考虑以下示例:

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中的doSomething
A中的doSomething

The output that I'm looking for in the console is:
doSomething in B
doSomething in A

推荐答案

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

With the code defined as I have it in the following fiddle: http://jsfiddle.net/JAAulde/psdym/2/

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

The best way is to .call() or .apply() A's method inside of B's:

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

或者,只需一举传递进入B.doSomething()的所有参数

Or, to simply pass all params that came into B.doSomething() in one fell swoop

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

一本很棒的书(由我的一位朋友撰写),用于学习JS中的各种继承模式,

An amazing book (written by a friend of mine) for learning about various patterns for inheritance in JS is http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X

这篇关于是否有与JavaScript原型继承等效的PHP“父级"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆