1.call(),apply()方法實現繼承
call方法的第一個參數的值賦值給類(即方法)中出現的this
call方法的第二個參數開始依次賦值給類(即方法)所接受的參數
apply方法的第一個參數和call相同,第二個參數為數組類型,這個數組中的每個元素依次賦值給類(即方法)所接受的參數
function animal(username){ this.username = username; this.sayHello = function(){ alert(this.username); } } function dog(username,password){ animal.call(this,username); this.password = password; this.sayPassword = function(){ alert(this.password); } } var child = new dog("lisi","123456"); child.sayHello(); child.sayPassword();
上面代碼就是用call來實現繼承,由於call有能改變this的特點,所以可以來實現繼承。而apply實現繼承幾乎和call是相似的,代碼如下:
function animal(username){ this.username = username; this.sayHello = function(){ alert(this.username); } } function dog(username,password){ animal.apply(this,new Array(username)); this.password = password; this.sayPassword = function(){ alert(this.password); } } var child = new dog("lisi","123456"); child.sayHello(); child.sayPassword();
下面我們來介紹第二種實現繼承的方式,利用原型鏈(prototype)來實現繼承。
function animal(){ } animal.prototype.hello = "lisi"; animal.prototype.sayHello = function(){ alert(this.hello); } function dog(){ } dog.prototype = new animal();
dog.prototype.constructor = dog; dog.prototype.password = "123456"; dog.prototype.sayPassword = function(){ alert(this.password); } var c = new dog(); c.sayHello(); c.sayPassword();
我們可以看到在dog方法里面,我們在dog.prototype下new了一個animal,目的是將animal中將所有通過prototype追加的屬性和方法都追加到dog,從而實現了繼承.
dog.prototype.constructor = dog;這句話是因為之前new了一下dog的constructor指向了animal,只要從新覆蓋即可。
最后一種實現繼承的方法對象冒充(不常用):
function animal(username){ this.username = username; this.sayHello = function(){ alert(this.username); } } function dog(username,password){ this.extend = animal; this.extend(username); delete this.metend; this.password = password; this.sayPassword = function(){ alert(this.password); } } var dog = new dog("lisi","123456"); dog.sayHello(); dog.sayPassword();
這種方法叫做對象冒充。實現原理:讓父類的構造函數成為子類的方法,然后調用該子類的方法,通過this關鍵字給所有的屬性和方法賦值。值得注意的是extend是一個自定義臨時屬性,在執行完函數一定要立即刪除。
this.extend是作為一個臨時的屬性,並且指向animal所指向的對象,
執行this.extend方法,即執行animal所指向的對象函數
銷毀this.extend屬性,即此時dog就已經擁有了animal的所有屬性和方法
