Javascript原型继承
我在谷歌上搜索了一个小时,但没有找到一个好答案。所以我的问题是:如何继承一个带有原型的类 我目前有以下解决方案:Javascript原型继承,javascript,oop,inheritance,prototype,Javascript,Oop,Inheritance,Prototype,我在谷歌上搜索了一个小时,但没有找到一个好答案。所以我的问题是:如何继承一个带有原型的类 我目前有以下解决方案: 唯一的问题是,BaseContent执行了两次。我不想那样。有更好的解决方案或修复方法吗?在JavaScript中实现继承的新方法是使用以下方法: function BaseContent(a, b) { this.propertyA = 'propertyA'; this.a = a; this.b = b; alert('x'); } BaseC
唯一的问题是,BaseContent执行了两次。我不想那样。有更好的解决方案或修复方法吗?在JavaScript中实现继承的新方法是使用以下方法:
function BaseContent(a, b) {
this.propertyA = 'propertyA';
this.a = a;
this.b = b;
alert('x');
}
BaseContent.prototype.funcA = function () {
alert(this.a + ', ' + this.b);
alert(this.propertyA);
};
function ContentA(a, b) {
BaseContent.call(this, a, b);
this.funcA();
}
ContentA.prototype = Object.create(BaseContent.prototype);
ContentA.prototype.constructor = ContentA;
ContentA.prototype.parent = BaseContent.prototype;
var Content = new ContentA('c', 'd');
请参见演示:
您可能应该阅读我的博客文章,以便更深入地了解JavaScript中的继承。我的建议是将其设置为更像这样
function BaseContent(a, b) {
this.propertyA = 'propertyA';
this.a = a;
this.b = b;
alert('x');
}
BaseContent.prototype = {
funcA: function () {
alert(this.a + ', ' + this.b);
alert(this.propertyA);
}
};
function ContentA(a, b) {
BaseContent.call(this, a, b);
this.funcA();
}
ContentA.prototype = BaseContent.prototype;
ContentA.prototype.constructor = ContentA;
var Content = new ContentA('c', 'd');
这里的示例是JSFIDLE,对于IE7/8兼容,您可以参考 请参阅JSFIDLE:
这在现代浏览器(EcmaScript 5标准)上可用,但在IE 8等浏览器上不可用。@Will-Hm好的,这不是大问题。但是如果有IE8的解决方案,那就太好了。@user2820280只需在程序的开头添加以下代码,它就能在每个浏览器中工作:
if(!Object.create)Object.create=(函数(工厂){return function(prototype){Factory.prototype=prototype;return new Factory;};}(函数(){})代码>
function BaseContent(a, b) {
this.propertyA = 'propertyA';
this.a = a;
this.b = b;
alert('x');
}
BaseContent.prototype = {
funcA: function () {
alert(this.a + ', ' + this.b);
alert(this.propertyA);
}
};
function ContentA(a, b) {
BaseContent.call(this, a, b);
this.funcA();
}
ContentA.prototype = BaseContent.prototype;
ContentA.prototype.constructor = ContentA;
var Content = new ContentA('c', 'd');
var BaseContent = Class.extend({
init: function (a, b) {
this.a = a;
this.b = b;
this.propertyA = 'propertyA';
alert('x');
},
funcA: function () {
alert(this.a + ', ' + this.b);
alert(this.propertyA);
}
});
var ContentA = BaseContent.extend({
init: function (a, b) {
this._super(a, b);
this.funcA();
}
});
var Content = new ContentA('c', 'd');