Javascript继承与原型
Javascript inheritance with prototype
我在谷歌上搜索了1个小时,但找不到一个好的答案。所以我的问题来了:我怎样才能继承一个类及其原型?
我目前有这个解决方案:http://jsfiddle.net/RdxYN/2/
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 = new BaseContent;
ContentA.prototype.constructor = ContentA;
ContentA.prototype.parent = BaseContent.prototype;
var Content = new ContentA('c', 'd');
唯一的问题是,BaseContent被执行了两次。我不想这样。有没有更好的解决方案或修复?
在 JavaScript 中实现继承的新方法是按如下方式使用 Object.create
:
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');
观看演示:http://jsfiddle.net/RdxYN/7/
您可能应该阅读我的博客文章 为什么原型继承很重要 以更深入地了解 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');
下面是 JSFiddle http://jsfiddle.net/LD8PX/
对于 IE 7/8 兼容,可以参考 简单 JavaScript 继承
参见 jsfiddle: http://jsfiddle.net/rHUFD/
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');
相关文章:
- 如何使用原型继承编写一个整洁灵活的复杂javascript应用程序
- $emit,$broadcast,原型继承
- 原型继承未按预期工作
- JavaScript中的原型继承.我可以称之为“超级”等价物吗?
- 不创建父对象的原型继承
- Javascript基本继承与Crockford原型继承
- JavaScript-构造函数参数和原型继承
- 使用Object.create作为原型的原型继承将[Object]作为实例的原型
- 原型继承返回值
- 如何进行JavaScript原型继承(原型链)
- Javascript-经理是一个人,但不是经理本身?功能/原型继承
- 模块化JS和原型继承
- 理解经典继承和原型继承之间的区别
- 理解Javascript原型继承
- AngularJS:多个工厂实例任何原型继承
- Javascript原型继承原型函数调用
- JavaScript中的原型继承是否演示了类型多态性
- 在JavaScript中使用带有原型继承的InstanceOf
- 原型继承和原型属性
- JavaScript-原型继承