正如您所发现的,JS 中的继承很棘手。也许比我更聪明的人可以在技术细节上告诉我们为什么,但一个可能的解决方案是使用非常小的 Base.js框架,由Dead Edwards提供。
编辑:我已经重组了原始代码以适应 Dean Edward 的框架。
一旦掌握了语法,继承就会正常工作。这是基于您的代码的可能解决方案:
var View = Base.extend({
constructor: function(location) {
if (location) {
this.location = location;
}
},
location: "UK",
getLocation: function() {
return this.location;
}
});
并扩展它:
var Paper = View.extend({
location: "US"
});
并对其进行测试:
var view = new View();
alert("The current location of the view is: " + view.getLocation());
var paper = new Paper();
alert("The location of the paper is: " + paper.getLocation());
alert("The current location of the view is: " + view.getLocation());
或者,可以通过以下方式实现相同的结果:
var Paper = View.extend();
和测试:
var view = new View();
alert("The current location of the view is: " + view.getLocation());
var paper = new Paper("US");
alert("The location of the paper is: " + paper.getLocation());
alert("The current location of the view is: " + view.getLocation());
两者都会产生三个警报:
The current location of the view is: UK
The location of the paper is: US
The current location of the view is: UK
我希望这有帮助!