面向对象之继承(类式继承)
function Aaa(){ this.name = '小明'; } Aaa.prototype.showName = function(){ alert(this.name); } function Bbb(){ } Bbb.prototype = new Aaa(); //实现继承 var b1 = new Bbb(); alert(b1.name); //‘小明’
一句话实现继承,是不是感觉很酷,以后就用他,但是,别急,因为他还有很多问题。。。。我们来看一下
console.log(b1.constractor); //ƒ Aaa(){this.name = '小明';}
我们首先看到构造constractor的指向不对了,我们修改指向
Bbb.prototype.constructor = Bbb;
除此之外还有一个很严重的问题,我们来看代码
function Aaa(){ this.name = [1,2,3]; } Aaa.prototype.showName = function(){ alert(this.name); } function Bbb(){ } Bbb.prototype = new Aaa(); //实现继承 Bbb.prototype.constructor = Bbb; var b1 = new Bbb(); b1.name.push(4); var b2 = new Bbb(); console.log(b2.name); //[1,2,3,4]
b2竟然找到了b1所push的4,这显然不行,我们继续改写
function Aaa(){ this.name = [1,2,3]; } Aaa.prototype.showName = function(){ alert(this.name); } function Bbb(){ Aaa.call(this); } Bbb.prototype.constructor = Bbb; var F = function(){}; F.prototype = Aaa.prototype; Bbb.prototype = new F(); var b1 = new Bbb(); b1.name.push(4); var b2 = new Bbb(); console.log(b2.name); //[1,2,3]
这样就完美了