在模擬javascrpt類的時候需要的一項工作就是construtor重新修訂問題,下面簡要說一下。
//說明一下constructor作用
function C(){};
function P(){};
C.prototype=P.prototype;//把C的原型指向了P的原型
C.prototype.constructor;// function P(){} C函數(shù)的原型的constructor是P函數(shù)。這里是原型鏈的內(nèi)容,即C的prototype上有一個constructor屬性,本來是指向C函數(shù)的。但是當C.prototype=P.prototype時,就指向了P。
其實construtor的作用就是重寫原型鏈,方式繼承的時候原型鏈更改到別的函數(shù)上。下面是一個例子
//父類
function Parent(){};
Parent.prototype.eating=function(){console.log("eat")};
Parent.prototype.driking=function (){console.log("drinking")};
//子類
function Children(){};
Children.prototype.playing=function(){console.log("playing")};
Children.prototype=Parent.prototype;
var children=new Children();
children.playing;//undefined
上面的代碼中,沒有重新修訂Children函數(shù)的原型指向,所以當重新調(diào)用chilren.playing的時候,就無法通過原型鏈查找到對應的方法。
下面的代碼是經(jīng)過修訂后的,就可以獲取原型鏈上對應的方法
//父類
function Parent(){};
Parent.prototype.eating=function(){console.log("eat")};
Parent.prototype.driking=function (){console.log("drinking")};
//子類
function Children(){};
Children.prototype=Parent.prototype;
//一定要先重新修訂contructor的指定,然后在在原型鏈prototype上掛函數(shù)。
Children.prototype.constructor=Children;
Children.prototype.playing=function(){console.log("playing")};
var children=new Children();
children.playing;//playing
最后總結(jié)一下就是,先父類===》》再子類===》》再繼承父類===》》重新修訂子類constructor===》》在子類原型掛接方法