JavaScript 的继承机制
1> 对象冒充,是JavaScript 和 ECMAScript实现继承的方法,在学习对象冒充实现继承前我们的先了解关键字 this 的使用,例如:
view plainfunction classA(sColor){ this.sColor = sColor; this.show = function(){alert(this.sColor);} } classA.prototype.say = function(){ alert("hello .."); } function classB(sColor,sName){ classA.call(this,sColor); this.sName = sName; } classB.prototype = new classA(); //note: no arguments and classB is a classA //只有此行后才可以给classB增加自己的属性和方法,否则会发生覆盖 classB.prototype.showName = function(){ alert(this.sName); } var a = new classA("blue"); a.show();//output blue a.say(); // output hello.. var b = new classB("red","BMW"); b.show(); // output red b.say(); //output hello.. b.showName();//output BMW
总结:通过以上几种方式多可以实现在Javascript中的继承,只有原型链这种方式不然实现多继承,但其优点在于classB的任何对象多属于classA,classB这两个类。