位置:首頁(yè) > 軟件操作教程 > 編程開(kāi)發(fā) > JavaScript > 問(wèn)題詳情

JavaScript 擴(kuò)展原型方法

提問(wèn)人:劉團(tuán)圓發(fā)布時(shí)間:2020-11-26

■設(shè)計(jì)思路

JavaScript允許通過(guò)prototype為原生類型擴(kuò)展方法,擴(kuò)展方法可以被所有對(duì)象調(diào)用。例如,通過(guò)Function, prototype為函數(shù)擴(kuò)展方法,然后為所有函數(shù)調(diào)用。

■設(shè)計(jì)代碼

為Function添加一個(gè)原型方法method,該方法可以為其他類型添加原型方法。

Function.prototype.method = function(name, func) {

    this.prototype[name] = func;

    return this;

};

■應(yīng)用代碼

【示例1】下面利用method擴(kuò)展方法為Number擴(kuò)展一個(gè)int原型方法。該方法可以對(duì)浮點(diǎn)數(shù)進(jìn)行取整。

Number.method('int', function() {

    return Math[this < 0 ? 'ceil' : 'floor'] (this);

});

console.log((-10 / 3).int());      //-3

    Number.method方法能夠根據(jù)數(shù)字的正負(fù)來(lái)判斷是使用Math.ceil還是Math.floor,這樣就避免了每次都編寫上面的代碼。

【示例2】下面利用method擴(kuò)展方法為String擴(kuò)展一個(gè)trim原型方法。該方法可以清除字符串左右 兩側(cè)的空字符。

String.method(1 trim1, function () {

    return this.replace(/^\s+ 丨\s+$/g, '');

});

console, log ('"' + " abc ".trim() + '"'); //返回帶引號(hào)的字符串 ''abc''

trim方法使用了一個(gè)正則表達(dá)式,把字符串中的左右兩側(cè)的空格符清除掉。

另外,可以使用hasOwnProperty方法過(guò)濾原型屬性或者私有屬性。

繼續(xù)查找其他問(wèn)題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部