如何在JavaScript中实现继承
How do you get inheritance working within JavaScript?
我希望构造函数Paper
继承构造函数View
。我已经读到需要一个临时构造函数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
的原型:
Paper.prototype.location.city = "US";
我发现View
的原型也被修改了!:
var view = new View();
console.log(view.location); //US! not UK
那么我的代码出了什么问题?如何在不影响父对象的情况下覆盖原型?
编辑:我已经重组了原始代码,以适应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中使用对象文字实现继承
- CoffeeScript 中的继承实现
- 在 JavaScript 中实现简单继承
- 使用Google闭包库的正确继承/子类实现剖析
- 如何在 javascript 中实现继承
- 如何实现 JavaScript 对象继承
- 在这种情况下在 JavaScript 中实现继承 [更具体地说是 node.js]
- 如何在 Screeps 对象中实现继承
- 在 AngularJS 指令中实现继承
- 在Javascript中使用寄生继承,是否可以实现内省实例方法
- 这种嵌套命名空间继承模式是否得到了很好的实现
- 用Selfish实现Javascript中的简单继承
- 我怎么能在Backbone中简单地实现类Sencha继承呢
- 使用父对象中的私有变量实现原型继承
- 如何在JavaScript中实现继承
- 我如何在JavaScript中实现这个java模式(使用继承)
- Javascript:如果不使用define prototype方法就可以实现继承,为什么还要使用它呢?
- 如何在Jquery UI控件中实现继承
- 在javascript中实现继承时出错
- 如何实现继承像&;var obj = new OpenLayers.Layer.WMS(.. ..)&;在Javascr