欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中子對象訪問父對象的方式詳解

 更新時間:2016年09月01日 10:12:39   作者:秋天的風,夏天的雨  
js中雖然沒有傳統(tǒng)面向?qū)ο蟮木幊陶Z言里子類訪問父類的特殊語法,但是我們可以根據(jù)需要造一個,接下來本文給大家分享在JavaScript中子對象訪問父對象的方式,需要的朋友可以參考下

在傳統(tǒng)面向?qū)ο蟮木幊陶Z言里,都會提供一種子類訪問父類的特殊語法,引文我們在實現(xiàn)子類方法往往需要父類方法的額外輔助。在這種情況下,子類通常會調(diào)用父類中的同名方法,最終以便完成工作。

javascript雖然沒有類似上述的特殊語法,但我們可以造一個??!

function her(){};
her.prototype.name = 'Anna';
her.prototype.toString = function(){
var const = this.constructor;
return const.uber ? this.const.uber.toString() + ',' + this.name : this.name;
}
function his(){};
var F = function(){};
F.prototype = her.prototype;
his.prototype = new F();
his.prototype.constructor = her;
his.uber = her.prototype;
his.prototype.name ='Jock';
function child(width, height){
this.width = width;
this.height = height;
}
var F = function(){};
F.prototype = his.prototype;
child.prototype = new F();
child.prototype.constructor = child;
child.uber = his.prototype;
child.prototype.name = 'Los';
child.prototype.getArea = function(){
return this.width * this.height;
}

我們在構(gòu)建關(guān)系的過程中,我們引入了一個uber屬性,并令其指向父及對象。

在這里,我們更新了以下內(nèi)容:

  1. 將usber屬性設(shè)置成指向父對象的引用;

  2. 對toString()方法進行了更新;

之前的toString()方法只是簡單的返回this.name,現(xiàn)在我們給他添加了額外的任務(wù),就是檢查this.constructor.usber屬性,如果存在就調(diào)用該屬性的toString()方法。

由于this.constructor本身是一個函數(shù),而this.constructo.usber是指向當前對象父級原型的引用,所以我們調(diào)用child實體的toString()方法時,其原型鏈上的toString()方法都會被調(diào)用。

var my = child(1,2);
my.toString() // Anna, Jock, Los

以上所述是小編給大家介紹的JavaScript中子對象訪問父對象的方式詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論