我希望构造函数 Paper
继承构造函数 View
。我读到需要有一个临时构造函数 new F()
,但是在我的代码中父类与子类原型(prototype)一起被修改:
function View() {};
function Paper() {};
View.prototype = {
location: {
"city": "UK"
}
}
function F() {};
F.prototype = View.prototype;
Paper.prototype = new F();
Paper.prototype.constructor = Paper;
所以当我尝试修改Paper
的原型(prototype)时:
Paper.prototype.location.city = "US";
我发现 View
的原型(prototype)也被修改了!:
var view = new View();
console.log(view.location); //US! not UK
那么我的代码有什么问题呢?如何在不影响父级的情况下覆盖原型(prototype)?
最佳答案
正如您所发现的,JS 中的继承很棘手。也许比我聪明的人可以告诉我们关于为什么的技术细节,但一个可能的解决方案是使用 very tiny 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
希望对您有所帮助!
关于javascript - 如何让继承在 JavaScript 中起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17861240/