js中物件的繼承

2021-06-19 19:00:34 字數 2715 閱讀 5165

//js中物件的繼承

//1.物件冒充(js中沒有訪問修飾符的概念)_可以實現多繼承(但會出現干擾,如果父類a和父類b中都定義了同名的屬性或方法,後面的繼承就會把前面的給替換掉了)不推薦

function parent(username)

}function child(username,password)

}var parent=new parent("lisi");

parent.sayhello();

var child=new child("zhangsan","12322");

child.sayhello();//繼承過來的方法

child.sayworld();

//理解:

理解這兒需要的知識是 成員方法中this的指代 this定義成員 直接給物件新增成員

function classb(scolor)//把此函式看作建構函式

下面的寫法能有同樣效果,可以幫助你理解:

function classb(scolor)//把此函式看作建構函式

var objb=new classb();

objb.newmethod("red");//在物件中呼叫該方法,同樣可以給物件新增那兩個成員,原寫法在建構函式中呼叫只是呼叫時間的區別,實質是相同的,能理解麼?

alert(objb.color);

引自:   

wzs_xyz的回答:

方法方式,call方法是定義在function物件中的方法,因此我們定義的每乙個函式都擁有call方法,可以通過函式名裡呼叫call方法,call方法的第乙個引數會被傳遞給函式中的this從第二個引數開始,逐一賦值給函式中的引數

function test(str,str2)

//var object=new object();

"zhangsan";

"lisi");

//delete object.method;//使用例項物件也可以實現物件冒充(不僅僅是在物件的定義中,可以動態的讓乙個物件繼承另乙個物件)

var object =new object();

object.name="zhangsan";

test.call(object,"shengsiyuan","hello");//將object賦給了test物件中的this--第乙個引數永遠會傳給this物件

//call方式繼承(用的比較多)

function parent(username)

}function child(username,password)

}var parent=new parent("zhangsan");

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

parent.sayhello();

child.sayhello();

child.sayworld();

function parent(username)

}function child(username,password)

}var parent=new parent("zhangsan");

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

parent.sayhello();

child.sayhello();

child.sayworld();

//4.原型鏈(prototype chain)方式實現物件的繼承,缺點:無法給建構函式傳入引數為屬性賦值

function parent()

parent.prototype.username="zhangsan";

parent.prototype.sayhello=function()

function child()

child.prototype=new parent();//讓子類的prototype指向父類的物件

child.prototype.password="123";

child.prototype.sayworld=function()

var child=new child();

child.username="lisi";

child.password="123";

child.sayhello();

child.sayworld();

//5.混合方式(推薦)--對於每乙個物件都有各自的屬性,各個物件的屬性之間不會相互干擾;每個物件共享同乙個方法

function parent(hello)

parent.prototype.sayhello=function()

function child(hello,world)

//var parent=new parent();

這樣不可以實現,只能為child的prototype賦parent物件

child.prototype=new parent();

child.prototype.sayworld=function()

var child=new child("zhangsan","293472");

child.sayhello();

child.sayworld();

js中物件繼承

一,js中物件繼承 js中有三種繼承方式 1.js原型 prototype 實現繼承 複製 如下 2.建構函式實現繼承 複製 如下 複製 如下 js手冊中對call的解釋 複製 如下 call 方法 呼叫乙個物件的乙個方法,以另乙個物件替換當前物件。call thisobj arg1 arg2 ar...

js中物件導向的繼承

參考 繼承 缺點 修改子類dog.prototype的同時也影響到了父類的animal.prototype 物件導向的拷貝繼承 上面 只是用了淺拷貝實現了物件的繼承,jquery中就是利用了拷貝繼承。function extend c,p if typeof p object else if win...

溫習js中物件的繼承

溫故而知新 xd 使用new 操作符呼叫建構函式,會經歷以下四個步驟 1.1.建立乙個新物件 1.2.將建構函式的作用域賦給新物件 因此 this 就指向了這個新物件 1.3.執行建構函式中的 為這個新物件新增屬性 1.4.返回新物件。當呼叫建構函式建立乙個新例項後,該例項的內部將包含乙個指標 內部...