[英]Is there an equivalent of PHP's 'parent' with javascript prototypal inheritance?
I'm using protypal inheritance and I would like to call an overridden method on the base class. 我正在使用protypal继承,我想在基类上调用重写方法。 In PHP I could do this using parent::functionName.
在PHP中,我可以使用parent :: functionName来完成此操作。 Is this possible using JavaScript protypal inheritance?
这可能是使用JavaScript protypal继承吗?
Consider the following example: 请考虑以下示例:
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();
The output that I'm looking for in the console is: 我在控制台中寻找的输出是:
doSomething in B 在B做一些事情
doSomething in A 做一件事
With the code defined as I have it in the following fiddle: http://jsfiddle.net/JAAulde/psdym/2/ 我将代码定义为以下小提琴: http : //jsfiddle.net/JAAulde/psdym/2/
The best way is to .call() or .apply() A's method inside of B's: 最好的方法是.call()或.apply()B的内部方法:
//Inside of B.doSomething
A.prototype.doSomething.call( this, arg1, arg2 );
Or, to simply pass all params that came into B.doSomething() in one fell swoop 或者,简单地通过一次性进入B.doSomething()的所有参数
//Inside of B.doSomething
A.prototype.doSomething.apply( this, arguments );
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 一本很棒的书(由我的一位朋友撰写),用于了解JS中的各种继承模式是http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X
from my own best practices, best to create 从我自己的最佳实践,最好的创造
var parent = ...;
when creating the object if reference to the parent is actually needed - which is not as much as one would expect. 在创建对象时,如果实际需要引用父对象 - 这并不像人们期望的那样多。 then use as desired.
然后根据需要使用。
I personally think the term "objects" is misleading in reference to javascript since 我个人认为“对象”一词在引用javascript时会产生误导
object == function == closure
essentially giving the tools for an objectness without limiting to formal object / inheritance constraints. 本质上为对象提供工具而不限制正式的对象/继承约束。 on the up side it makes a very fluid, mutable language;
从好的方面来说,它是一种非常流畅,可变的语言; on the downside, you need to fill in yourself missing pieces when needed.
在缺点方面,您需要在需要时填写自己缺失的部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.