Javascript继承原型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Javascript继承原型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1299字,纯文字阅读大概需要2分钟。
内容图文
![Javascript继承原型](/upload/InfoBanner/zyjiaocheng/817/e7534e2c0d9541c7bc652eeb0a539b34.jpg)
我用谷歌搜索了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/
您应该阅读我在Why Prototypal Inheritance Matters上的博客文章,以便更深入地了解JavaScript中的继承.
内容总结
以上是互联网集市为您收集整理的Javascript继承原型全部内容,希望文章能够帮你解决Javascript继承原型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。