如何调用父构造函数? [英] how to call parent constructor?
本文介绍了如何调用父构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码段。
function test(id) { alert(id); }
testChild.prototype = new test();
function testChild(){}
var instance = new testChild('hi');
是否可以获得 alert('hi')
?我现在得到 undefined
。
Is it possible to get alert('hi')
? I get undefined
now.
推荐答案
这就是你在CoffeeScript中这样做的方法:
That's how you do this in CoffeeScript:
class Test
constructor: (id) -> alert(id)
class TestChild extends Test
instance = new TestChild('hi')
不,我没有开始圣战。相反,我建议看看生成的JavaScript代码,看看如何实现子类化:
Nope, I'm not starting a holy war. Instead, I'm suggesting to take a look at resulting JavaScript code to see how subclassing could be implemented:
// Function that does subclassing
var __extends = function(child, parent) {
for (var key in parent) {
if (Object.prototype.hasOwnProperty.call(parent, key)) {
child[key] = parent[key];
}
}
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
// Our code
var Test, TestChild, instance;
Test = function(id) { alert(id); };
TestChild = function() {
TestChild.__super__.constructor.apply(this, arguments);
}; __extends(TestChild, Test);
instance = new TestChild('hi');
// And we get an alert
在< a href =http://jsfiddle.net/NGLMW/3/ =noreferrer> http://jsfiddle.net/NGLMW/3/ 。
为了保持正确,与CoffeeScript输出相比,代码稍作修改并注释为更具可读性。
To stay correct, the code is slightly modified and commented to be more readable, compared to CoffeeScript output.
这篇关于如何调用父构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文