JS的继承、多态
构造函数的继承
JS中的继承是一种对象冒充来实现继承功能,而不是其他语言中定义的继承
funciton A(color){ this.color=color; this.saycolor=function() { alert(this.color); } } function B (color){ this.AB=A; this.AB(color); delete this.AB; }
注释:B函数中 使用this.AB=A 其实就是用AB这个属性等于A函数,也就是AB具有了A函数的属性及其方法。通过this.AB(color),也就是调用了A函数的方法,此时A中的this指向AB,this.AB的this指向B,也就使B具有了相应的属性和方法。使用过后要删除AB,其实就是删除A和B之间的连接,因为这里的继承和其他语言中的继承不同,他其实就是一种调用。如果不进行删除,很有可能在通过调用B的同时对A进行了操作。也正因为这个原因,这种操作时,必须删除连接后在定义B的相关属性和方法。
(定义很绕嘴,掌握其使用方法即可,简单的定义就是,子函数中的一个属性等于父函数,通过this.函数就可以使用父函数的功能呢,使用完了就删除再做自己该干的事)
例如:
function B (color){ this.AB=A; this.AB(color); delete this.AB; this.doors=null; this.saydoors=function(){ alert(this.doors) } }
Call()方法
call方法是与经典的对象冒充方法最相似的方法.它的第一个参数用作this的对象,其他参数都直接传递给函数自身.
function ClassA(sColor) { this.color = sColor; this.sayColor=function() { alert(this.color); } } function ClassB(sColor,sName) { ClassA.call(this,sColor) this.name = sName; this.sayName= function() { alert(this.name); } } //call var objB = new ClassB(“red”,”zhang”); objB.sayColor(); //output “red” objB.sayName(); //output “zhang”
}apply()方法apply()方法有两个参数,用作this的对象和要传递给函数的参数的数组.
function ClassA(sColor) { this.color = sColor; this.sayColor=function() { alert(this.color); } } function ClassB(sColor,sName) { ClassA.apply(this,new Array(sColor)); this.name = sName; this.sayName= function() { alert(this.name); } } //call var objB = new ClassB(“red”,”zhang”); objB.sayColor(); //output “red” objB.sayName(); //output “zhang”
原型链继承
function ClassA(){ } ClassA.prototype.color = “red”; ClassA.prototype.sayColor = function(){ alert(this.color); } function ClassB(){ } // function ClassB(){ } ClassB.prototype = new ClassA(); ClassB.prototype.name = “”; ClassB.prototype.sayName = function(){ alert(this.name); } //call var objA = new ClassA(); var objB = new ClassB(); objA.color = "blue"; objB.color = "yellow"; objB.name = "zhang"; objA.sayColor(); //output “blue” objB.sayColor(); //output “yellow”; objB.sayName(); //output “zhang”
混合模式
function ClassA(sColor) { this.color = sColor; } ClassA.prototype.sayColor = function(){ alert(this.color); } //ClassB function ClassB(sColor,sName){ ClassA.call(this,sColor); this.name = sName; } ClassB.prototype = new ClassA(); ClassB.prototype.sayName = function(){ alert(this.name); } //call var objA = new ClassA(“red”); var objB = new ClassB(“blue”,”zhang”); objA.sayColor(); //output “red” objB.sayColor(); //output “blue” objB.sayName(); //output “zhang”