使用prototype属性的javascript继承
javascript inheritance using the prototype property
我正在尝试用javascript进行继承。首先,在网上我发现了这个
function A() {}
function B(){}
B.prototype = new A() ;
B.prototype.constructor = B ;
这是有效的,但是当我使用B的原型属性时,它就不再有效了(http://jsfiddle.net/jeanluca/eQBUx/)
function A() {}
A.prototype.bar = function(){ return 'A'; }
function B() {}
B.prototype.bar = function(){ return 'B'; }
我知道你可以做
function B(){ this.bar = function(){ ... } } ;
但我认为这肯定比使用原型来定义它要慢。那么,在第二种情况下,我该如何继承呢?
Thnx
这是您的代码:
function A() {}
A.prototype.bar = function(){ return 'A';}
function B() {}
B.prototype.bar = function(){ return 'B'; }
B.prototype = new A() ; // replaces B's "bar" with A's "bar
var b = new B ;
console.log(b.bar());
正如你所看到的,问题出在你的第六行。您首先在第5行将B.prototype.bar
设置为函数,然后在第6行立即将B.prototype
设置为new A
(实际上撤消了您在第5行将执行的操作)。解决方案是将第6行放在第5行之前:
function A() {}
A.prototype.bar = function(){ return 'A';}
function B() {}
B.prototype = new A() ; // now it will work
B.prototype.bar = function(){ return 'B'; }
var b = new B ;
console.log(b.bar());
亲自观看演示:http://jsfiddle.net/eQBUx/1/
此外,我同意Bergi的观点:停止使用new
关键字。
更新:阅读您的评论并更详细地了解您的问题后,我建议您使用我的augment
库进行继承:
var A = Object.augment(function () {
this.constructor = function () {};
this.bar = function () {
return "A";
};
});
var B = A.augment(function (base) {
this.constructor = function () {};
this.bar = function () {
return "B" + base.bar.call(this);
};
});
var b = new B;
console.log(b.bar());
查看演示:http://jsfiddle.net/eQBUx/2/
使用this
分配属性会破坏原型链。它的效率非常低,而且你不能用它来获得继承。所以不是吗?
您正在原型对象上创建一个属性,然后将其完全替换。反之亦然,在新对象上创建bar
方法。不要使用new
!
function B() {}
// first create the prototype object
B.prototype = Object.create(A.prototype);
// then assign properties on it
B.prototype.bar = function(){ return 'B'; }
相关文章:
- 关于Javascript继承,我可以'我不明白
- Javascript继承代码集
- Javascript:继承原型而不重新定义构造函数
- JavaScript继承:未捕获的范围错误:超过了最大调用堆栈大小
- JavaScript继承:为什么从实例复制
- javascript继承中正确的原型做作是什么
- 没有原型的Javascript继承
- Javascript继承-使用.call方法
- 运行Javascript继承代码时出错
- Javascript继承构造函数
- Javascript继承和封装,高效完成
- 具有简洁原型赋值语法的Javascript继承
- Javascript继承的问题&基类原型
- JavaScript继承构造函数.prototype
- javascript继承说明
- Javascript继承:从超类的方法设置子类的属性
- 简单的 Javascript 继承示例
- 具有意外行为的 JavaScript 继承
- 基于实例的 JavaScript 继承
- 为什么 JavaScript 继承是这样工作的