javaScript函數(shù)與Function

1.函數(shù),對象和類理解

在javaScript中定義一個函數(shù)的同時就相當于定義了一個同名的類,如

function ?Student(name,age){

? ? ? ? this.age=age;

? ? ? ? this.name=name;

? ? ? ? this.type="student";

? ? ? ? this.print=function(){

? ? ? ? ? ? ? ? ? ? ? ? document.write(" "+this.name+this.age+ “ ”);

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }

}

var s=new Student("whz",24);

在這里定義一個Student函數(shù),同時也是一個類

2.prototype屬性

Function的prototype屬性保存著函數(shù)的原型對象,prototype在英語中是原型的意思,在這里屬于Object的屬性,所以每一個類都具有該屬性

當我們的類中有固定的屬性和方法時,我們用prototype來定義這樣可以節(jié)省內(nèi)存,簡化代碼

舉例:

var xiaoming=new Student("xiaoming",22);

xiaoming.print();

var xiaohei=new Studnet("xiaohei",22);

xiaohei.print();

上面的代碼中我們重復(fù)調(diào)用了type屬性和print()方法,這兩個屬于每一Student對象共同的屬性,方法,在javaScript中我們使用prototype來實現(xiàn).。在該示例中每生成一個實例,都會重復(fù)生成type屬性和eat( )方法從而浪費了內(nèi)存。這時候,prototype(原型對象)就派上用場了。

舉例:

function ?Student(name,age){

? ? ? ? this.age=age;

? ? ? ? this.name=name;? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

}

Student.prototype.type="student";

Student.prototype.print=function (){

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? document.write('sdfsdfsdfds");

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }

在JavaScript中實例可繼承prototype的屬性和方法;也就是說:我們可把那些不變的屬性和方法直接定義在prototype對象上

3.call()和apply()的使用

call( )和apply( )用于調(diào)用當前Function對象并與此同時改變函數(shù)內(nèi)的this指針引用。換句話說:call( )和apply( )切換了函數(shù)執(zhí)行時的上下文(this值)。call( )和apply( )是Function對象的方法,每個函數(shù)都能調(diào)用它們。先來瞅瞅call( )

var ?name="小明";

var boy={name:"大雄"};

function ?introduce(message){

????????????document.writeln(message+",我的名字是"+this.name+" ");?

?}

?introduce("hello");?

?introduce.call(this,"hello");

?introduce.call(boy,"大家好");

輸出結(jié)果大家應(yīng)該能猜到了:hello,我的名字是小明

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? hello,我的名字是小明

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 大家好,我的名字是大雄

一般來說,this指的是window窗口,我們定義的this.name 和this.print方法都是屬于window窗口的,可以看到,第二個this只是重復(fù)強調(diào)了一遍introduce方法中的this.name中的this為window窗口。

而第三個方法中我們用call將切換了this,將其改為boy,這樣就相當于boy類中有了introduce方法

,可以想到事實上這就是javaScript中繼承的雛形?。。。?/b>

apply( )與Function對象的call( )函數(shù)作用相同,只不過call( )函數(shù)是將Function對象的參數(shù)一個個分別傳入,而apply( )函數(shù)是將Function對象的參數(shù)以一個數(shù)組或以arguments對象的形式整體傳入。其余東西,不再贅述。

boy.apply(this,arguments);//可能會奇怪怎么會用類.apply()呢?要記住javaScript中函數(shù)就是類,類就是函數(shù)啊,這里是把boy當函數(shù)使用了

4、length屬性

Function的length屬性返回函數(shù)的輸入?yún)?shù)的個數(shù)

5.arguments

Function的arguments代表正在執(zhí)行的函數(shù)的內(nèi)置屬性,它包含了調(diào)用該函數(shù)時所傳入的參數(shù)信息。例如:可使用arguments.length得到參數(shù)的個數(shù);可利用arguments[index]得到參數(shù)的值。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容