gpt4 book ai didi

javascript - 是否有等效于 PHP 的 'parent' 的 javascript 原型(prototype)继承?

转载 作者:行者123 更新时间:2023-11-29 15:04:16 24 4
gpt4 key购买 nike

我正在使用原型(prototype)继承,我想在基类上调用一个重写的方法。在 PHP 中,我可以使用 parent::functionName 来做到这一点。这可能使用 JavaScript 原型(prototype)继承吗?

考虑以下示例:

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 中做点什么
在 A 中做某事

最佳答案

使用我在以下 fiddle 中定义的代码:http://jsfiddle.net/JAAulde/psdym/2/

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

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

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

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

一本学习 JS 中各种继承模式的好书(我的一个 friend 写的)是 http://www.amazon.com/JavaScript-Design-Patterns-Recipes-Problem-Solution/dp/159059908X

关于javascript - 是否有等效于 PHP 的 'parent' 的 javascript 原型(prototype)继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5508393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com