国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Javascript如何實(shí)現(xiàn)擴(kuò)充基本類型

瀏覽:3日期:2023-10-17 11:18:07

可以通過給Function.prototype增加方法來使得該方法對所有函數(shù)可用。

通過給Function.prototype增加一個(gè)method方法,下次給對象增加方法的時(shí)候就不必鍵入prototype這幾個(gè)字符了。

Function.prototype.method=function(name,func){ this.prototype[name]=func; return this;}

一、JavaScript增加整數(shù)類型

JavaScript沒有專門的整數(shù)類型,但有時(shí)候確實(shí)只需要提前數(shù)字中的整數(shù)部分。

可以給Number.prototype增加一個(gè)integer方法。

inter()方法根據(jù)數(shù)字的正負(fù)來判斷是使用Math.ceiling還是Math.floor。

Number.method(’integer’,function(){ return Math[this<0?’ceil’:’floor’](this);});document.writeln((-10/3).integer());//-3

二、JavaScript缺少一個(gè)移除字符串首尾空白的方法

String.method(’trim’,function(){ return this.replace(/^s+|s+$/g,’’);});document.writeln(’ ' ’+' neat '.trim() +’ ' ’);//' neat '

基本類型的原型是公用結(jié)構(gòu),所以在類庫混用時(shí)務(wù)必小心。一個(gè)保險(xiǎn)的做法就是只在確定沒有該方法時(shí)才添加它。

Function.prototype.method=function(name,func){ if(!this.prototype[name]){ this.prototype[name]=func; } return this;}

new前綴去調(diào)用一個(gè)函數(shù)

Function.method(’new’,function () { //創(chuàng)建一新對象,它繼承自構(gòu)造器函數(shù)的原型對象。 var that=Object.create(this.prototype); //調(diào)用構(gòu)造器函數(shù),綁定-this-到新對象上。 var other=this.apply(that,arguments); //如果它的返回值不是一個(gè)對象,就返回該對象。 return (typeof other===’object’&&other)||that;});

superior

Object.method(’superior’,function(name){ //傳入方法名name var that=this,method=that[name]; return function(){ return method.apply(that,argumetns); }});

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 淮滨县| 新蔡县| 大同县| 密云县| 玉山县| 河东区| 玛多县| 苍山县| 松滋市| 新源县| 博野县| 长岛县| 墨江| 乌兰察布市| 合山市| 额敏县| 阜新市| 西青区| 墨江| 怀来县| 定南县| 迁西县| 昔阳县| 盐池县| 郯城县| 安仁县| 双柏县| 尚义县| 永平县| 九龙坡区| 鄯善县| 绍兴县| 沙河市| 元朗区| 惠水县| 东兰县| 曲靖市| 隆化县| 松桃| 台北市| 淮南市|