有人可以解釋這個函數嗎?object函數和對象Array - Object.prototype.toString.call
function b(a) {
return "[object Function]" == Object.prototype.toString.call(a)
}
而且
function c(a) {
return "[object Array]" == Object.prototype.toString.call(a)
}
有人可以解釋這個函數嗎?object函數和對象Array - Object.prototype.toString.call
function b(a) {
return "[object Function]" == Object.prototype.toString.call(a)
}
而且
function c(a) {
return "[object Array]" == Object.prototype.toString.call(a)
}
您從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)
)
當你調用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
方法