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

JavaScript 檢測(cè)原型對(duì)象

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

■知識(shí)點(diǎn)

在JavaScript中,F(xiàn)unction對(duì)象預(yù)定義了 prototype屬性,該屬性指向一個(gè)原型對(duì)象。當(dāng)定義構(gòu)造函數(shù)時(shí),系統(tǒng)會(huì)自動(dòng)創(chuàng)建一個(gè)對(duì)象,并傳遞給prototype屬性,這個(gè)對(duì)象被稱為原型對(duì)象。原型對(duì)象可以存儲(chǔ)構(gòu)造類型的原型屬性,以便讓所有實(shí)例對(duì)象共享。

■實(shí)例設(shè)計(jì)

下面的代碼為自定義類型函數(shù)定義兩個(gè)原型成員。

var f = function (){}

f.prototype = {

    a : 1,

    b : function (){

        return 2;

    }

}

console.log (f.prototype, a) ;         //讀取函數(shù)的原型對(duì)象的屬性a,返回1

console.log (f. prototype.b() ) ; //讀取函數(shù)的原型對(duì)象的屬性b,返回2

當(dāng)使用new運(yùn)算符調(diào)用函數(shù)時(shí),就會(huì)創(chuàng)建一個(gè)實(shí)例對(duì)象,這個(gè)實(shí)例對(duì)象將繼承構(gòu)造函數(shù)的原型對(duì)象中所有屬性。

var o = new f (); //實(shí)例對(duì)象

console.log (o.a); //訪問原型對(duì)象的屬性

console.log (o.b ()); //訪問原型對(duì)象的厲性

為了方便判定,Object對(duì)象定義了 isPrototypeOf()方法,該方法可以檢測(cè)一個(gè)對(duì)象的原型對(duì)象。針對(duì)上面的示例,可以判斷f.prototype就是對(duì)象o的原型對(duì)象,因?yàn)槠浞祷刂禐閠rue。

var b = f.prototype.isPrototypeOf(o); 

console.log(b);

■小結(jié)

下面的示例演示了各種特殊對(duì)象的原型對(duì)象。

函數(shù)的原型對(duì)象可以是Object.prototype或者是Function.prototype:

    var f = function (){}

    console.log(Object.prototype.isPrototypeOf(f));                //返回 true

    console.log(Function .prototype.isPrototypeOf(f));        //返回 true

Object和Function對(duì)象的原型對(duì)象比較特殊:

    console.log(Function .prototype.isPrototypeOf(Object));     //返回 true

    console.log(Object.prototype.isPrototypeOf(Function));     //返回 true

Object.prototype 和 Function.prototype 的原型對(duì)象不是Object.prototype,而 Function.prototype 的原型對(duì)象可以是Function.prototype,但是Object.prototype的原型對(duì)象絕對(duì)不是Function .prototype:

    console.log (Object.prototype.isPrototypeOf (Object.prototype));          //返回 false

    console.log (Object.prototype.isPrototypeOf (Function .prototype));  //返回 true

    console.log (Function.prototype.isPrototypeOf (Function.prototype));      //返回 false 

    console.log (Function.prototype.isPrototypeOf (Object.prototype));         //返回 false

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

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