如何在JavaScript中实现继承?
我希望构造函数如何在JavaScript中实现继承?,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,我希望构造函数文件继承构造函数视图。我已经读到需要一个临时构造函数new F(),但是父类和子类原型在我的代码中一起被修改: function View() {}; function Paper() {}; View.prototype = { location: { "city": "UK" } } function F() {}; F.prototype = View.prototype; Paper.prototype = new F(); Pape
文件
继承构造函数视图
。我已经读到需要一个临时构造函数new F()
,但是父类和子类原型在我的代码中一起被修改:
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.location.city = "US";
我发现视图的原型也被修改了!:
var view = new View();
console.log(view.location); //US! not UK
那么我的代码怎么了?如何在不影响父对象的情况下覆盖原型?正如您所发现的,JS中的继承很棘手。也许有比我更聪明的人可以在技术细节上告诉我们为什么,但是一个可能的解决方案是使用框架,这是一个很好的解决方案
编辑:我已经重新构造了原始代码,以适应迪安·爱德华的框架。
一旦掌握了语法,继承将正常工作。以下是基于您的代码的可能解决方案:
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
我希望这有帮助 可能重复的,你能根据OP的问题调整框架,而不是从链接页面复制示例吗?我担心它不会工作。@Bergi完成了,尽管我今天下午才能自己测试。请在什么时候测试它,我相信这仍然会显示问题。@Bergi修复了!希望这至少部分回答了OP的问题。