2017-02-13 66 views
1

JavaScript的instanceof運算符返回false

var name = new String("green"); 
 
    console.log(name instanceof String);//returns false 
 
    var color= new String("green"); 
 
    console.log(color instanceof String);//returns true

在這裏,第一個是返回false,第二個是返回true,什麼是如果我使用變量名就顯示錯誤 並有原因喜歡的名字作爲變量名

+0

保留字的http://www.w3schools.com/js/js_reserved.asp – prasanth

+1

'window.name'在JavaScript中有特殊含義。它不應該被用作全局變量。 – 4castle

+1

@JLRishe它被列在*「JavaScript對象,屬性和方法」* – 4castle

回答

2

由於name以JavaScript保留keywrd(不是真的,但保留全局對象),其中發生錯誤拋出的任何變量,它直接指向window.name

你可以嘗試_name,也將努力

var _name = new String("green"); 
console.log(_name instanceof String);//returns true 
1

這是因爲你試圖覆蓋global name變量,其中有一個setter自動任何你分配給它轉換爲字符串(new String創建String對象,它與字符串不一樣)。

解決方案:使用不同的變量名稱或正確地限定變量的範圍。

console.log(typeof name); // string 
 

 
var name = new String("green"); 
 

 
console.log(typeof name); // still string 
 

 
var color = new String("green"); 
 

 
console.log(typeof color); // object 
 

 
// create new scope 
 
function myFunction() { 
 
    var name = new String("green"); 
 

 
    console.log(typeof name); // object 
 

 
    var color = new String("green"); 
 

 
    console.log(typeof color); // object 
 
} 
 

 
myFunction();

0

instanceof運算測試對象是否在其原型鏈有一個構造的原型屬性。

在第一種情況下,它檢查原型鏈,發現它未定義並返回false。這不僅與name,但下面的例子中也將返回false

var simpleStr = 'This is a simple string'; 
console.log(simpleStr instanceof String); 

的另一種方法是使用typeofconstructor 同樣的例子將對以下情況

var simpleStr = 'This is a simple string'; 
simpleStr .constructor == String 

對於返回true進行測試你的例子也如果你做

var name = new String("green"); 
name .constructor == String 

它會返回true

+0

這個問題與OP對'instanceof'操作符的理解不是問題。 OP詢問爲什麼兩個變量的行爲不同,它們都有'new String('...')'分配給它們。 – JLRishe

相關問題