3 回答

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
實(shí)例
左側(cè)(LHS)操作數(shù)是要測(cè)試到右側(cè)(RHS)操作數(shù)的實(shí)際對(duì)象,右側(cè)對(duì)象是類的實(shí)際構(gòu)造函數(shù)?;径x是:
Checks the current object and returns true if the object
is of the specified object type.
這是一些很好的示例,這是直接從Mozilla開發(fā)人員網(wǎng)站獲取的示例:
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral"; //no type specified
color2 instanceof String; // returns false (color2 is not a String object)
值得一提的是instanceof,如果對(duì)象繼承自類的原型,則其值為true:
var p = new Person("Jon");
p instanceof Person
這是p instanceof Person是因?yàn)檎嬲齪的繼承Person.prototype。
根據(jù)OP的要求
我添加了一個(gè)帶有示例代碼和解釋的小示例。
聲明變量時(shí),可以為其指定特定類型。
例如:
int i;
float f;
Customer c;
上面顯示一些變量,即i,f和c。這些類型是integer,float和用戶定義的Customer數(shù)據(jù)類型。諸如此類的類型可以適用于任何語言,而不僅僅是JavaScript。但是,使用JavaScript聲明變量時(shí),您沒有顯式定義類型var x,x可能是數(shù)字/字符串/用戶定義的數(shù)據(jù)類型。因此,instanceof它執(zhí)行的操作是檢查對(duì)象以查看其是否為指定的類型,因此從上面開始Customer我們可以執(zhí)行以下操作:
var c = new Customer();
c instanceof Customer; //Returns true as c is just a customer
c instanceof String; //Returns false as c is not a string, it's a customer silly!
上面我們已經(jīng)看到了c使用類型聲明的Customer。我們已經(jīng)對(duì)其進(jìn)行了更新,并檢查了它是否為類型Customer。當(dāng)然可以,它返回true。然后仍然使用該Customer對(duì)象,我們檢查它是否為String。不,絕對(duì)不是String我們更新的Customer對(duì)象而不是String對(duì)象。在這種情況下,它返回false。
真的就是這么簡(jiǎn)單!

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
此處的其他答案是正確的,但它們并未instanceof涉及實(shí)際的工作方式,這可能是一些語言律師所感興趣的。
JavaScript中的每個(gè)對(duì)象都有一個(gè)原型,可以通過該__proto__屬性訪問。函數(shù)還具有一個(gè)prototype屬性,該屬性是__proto__它們創(chuàng)建的任何對(duì)象的初始值。創(chuàng)建函數(shù)時(shí),會(huì)為其提供一個(gè)唯一的對(duì)象prototype。該instanceof操作員使用這種獨(dú)特性給你一個(gè)答案。以下是instanceof可能的樣子,如果你寫一個(gè)函數(shù)。
function instance_of(V, F) {
var O = F.prototype;
V = V.__proto__;
while (true) {
if (V === null)
return false;
if (O === V)
return true;
V = V.__proto__;
}
}
這基本上是ECMA-262版本5.1(也稱為ES5)第15.3.5.3節(jié)的措辭。
請(qǐng)注意,可以將任何對(duì)象重新分配給函數(shù)的prototype屬性,并且可以__proto__在構(gòu)造對(duì)象后重新分配對(duì)象的屬性。這將給您一些有趣的結(jié)果:
function F() { }
function G() { }
var p = {};
F.prototype = p;
G.prototype = p;
var f = new F();
var g = new G();
f instanceof F; // returns true
f instanceof G; // returns true
g instanceof F; // returns true
g instanceof G; // returns true
F.prototype = {};
f instanceof F; // returns false
g.__proto__ = {};
g instanceof G; // returns false
添加回答
舉報(bào)