2016-10-15 40 views

回答

2

您從Object.prototype借貸的方法toString找出如果你正在傳遞到其中一個功能值是Function構造函數或Array構造的一個實例。

直接從對象中使用toString原型將覆蓋Array.prototype和Function.prototype上具有不同行爲的toString

function b(a) { 
 
    return "[object Function]" == Object.prototype.toString.call(a) 
 
} 
 

 
console.log(
 
    Object.prototype.toString.call(b), 
 
    b(b) 
 
)

1

當你調用toString上的功能,它返回[object Function]
當您在陣列上調用toString時,它將返回[object Array]

如果無論是在通過第一種功能檢查是一個函數

function b(a) { 
 
    return "[object Function]" == Object.prototype.toString.call(a) 
 
} 
 

 
var x = b('s'); // false 
 
var y = b(function() {}); // true 
 

 
console.log(x, y)

第二檢查是否任何在被傳遞是一個數組

function c(a) { 
 
    return "[object Array]" == Object.prototype.toString.call(a) 
 
} 
 

 
var x = c('s'); // false 
 
var y = c([1,2,3]); // true 
 

 
console.log(x, y)

因爲總是使用Object.prototype.toString,所以即使字符串和數字也可以這樣檢查,因爲它不只是調用它自己的值toString方法