js實現繼承的5種方式

2022-04-09 11:31:23 字數 1856 閱讀 9459

1.物件冒充:

function

parent(username)

}

function

child(username,password)

}

var parent = new parent("zhangsan");

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

parent.hello();

child.hello();

child.world();

2.call()方法:

function

parent(username)

}

function

child(username,password)

}

var parent = new parent("zhangsan");

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

parent.hello();

child.hello();

child.world();

function

parent(username)

}

function

child(username,password)

}

var parent = new parent("zhangsan");

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

parent.hello();

child.hello();

child.world();

4.原型鏈:

function

person(){}

person.prototype.hello = "hello";

person.prototype.sayhello = function

()

function

child(){}

child.prototype = new person();//

這行的作用是:將parent中將所有通過prototype追加的屬性和方法都追加到child,從而實現了繼承

child.prototype.world = "world";

child.prototype.sayworld = function

()

var c = new

child();

c.sayhello();

c.sayworld();

5.call()方法與原型鏈混合:

function

parent(hello)

parent.prototype.sayhello = function

()

function

child(hello,world)

child.prototype = new parent();//

將父類的方法繼承過來

child.prototype.sayworld = function()

var c = new child("zhangsan","lisi");

c.sayhello();

c.sayworld();

js實現繼承的5種方式

js是門靈活的語言,實現一種功能往往有多種做法,ecmascript沒有明確的繼承機制,而是通過模仿實現的,根據js語言的本身的特性,js實現繼承有以下通用的幾種方式 1.使用物件冒充實現繼承 該種實現方式可以實現多繼承 實現原理 讓父類的建構函式成為子類的方法,然後呼叫該子類的方法,通過this關...

js實現繼承的5種方式

js是門靈活的語言,實現一種功能往往有多種做法,ecmascript沒有明確的繼承機制,而是通過模仿實現的,根據js語言的本身的特性,js實現繼承有以下通用的幾種方式 1.使用物件冒充實現繼承 該種實現方式可以實現多繼承 實現原理 讓父類的建構函式成為子類的方法,然後呼叫該子類的方法,通過this關...

js實現繼承的5種方式

js是門靈活的語言,實現一種功能往往有多種做法,ecmascript沒有明確的繼承機制,而是通過模仿實現的,根據js語言的本身的特性,js實現繼承有以下通用的幾種方式 1.使用物件冒充實現繼承 該種實現方式可以實現多繼承 實現原理 讓父類的建構函式成為子類的方法,然後呼叫該子類的方法,通過this關...