JS實現繼承的幾種方法

2021-08-03 01:15:50 字數 2703 閱讀 7096

call方法的第乙個引數的值賦值給類

(即方法

)中出現的

this

call方法的第二個引數開始依次賦值給類

(即方法

)所接受的引數

call

相同,第二個引數為陣列型別,這個陣列中的每個元素依次賦值給類

(即方法

)所接受的引數

this

的指向,我們就是利用它的這個特性來實現繼承的。

補充知識點:

function animal(username){

this.username = username;

this.sayhello = function(){

alert(this.username);

function dog(username,password){

animal.call(this,username);//=this.animal(username);相當於

this

呼叫了這個方法

this.password = password;

this.saypassword = function(){

alert(this.password);

var child = new dog("lisi","123456");

child.sayhello();

child.saypassword();

上面**就是用call來實現繼承,由於

call

有能改變

this

的特點,所以可以來實現繼承。而

實現繼承幾乎和

call

是相似的,**如下:

function animal(username){

this.username = username;

this.sayhello = function(){

alert(this.username);

function dog(username,password){

this.password = password;

this.saypassword = function(){

alert(this.password);

var child = new dog("lisi","123456");

child.sayhello();

child.saypassword();

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.extend;

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

的所有屬性和方法

js實現繼承的幾種方法

js實習繼承的幾種方法 1.for in繼承 function person function son var p new person var s new son for var k in p console.log s.name 水煮魚 console.log s.age 18 2.原型繼承 f...

js繼承的幾種方法

繼承的幾種方法 1.傳統形式 繼承過多沒用的東西 father.prototype.name hzl function father var father new father son.prototype father function son var son new son console.log...

js原型繼承的幾種方法

首先建立乙個建構函式,並為其設定私有屬性和公有屬性。定義乙個人類 function person name 原型方法 person.prototype.eat function food 原型繼承有很多種方法,接下來就記錄下我已知的幾種方法。第一種 原型鏈繼承 重點圈起來 將父類例項賦值給子類原型物...