rya*_*nve 9 javascript types typechecking
我明白你为什么需要使用Object.prototype.toString()或String()进行类型检查数组,但不是的typeof足够的类型检查功能和字符串?例如,MDN for Array.isArray上的polyfill使用:
Object.prototype.toString.call(arg) == '[object Array]';
Run Code Online (Sandbox Code Playgroud)
在数组的情况下非常清楚,因为你不能typeof用来检查数组.Valentine使用instanceof:
ar instanceof Array
Run Code Online (Sandbox Code Playgroud)
但对于字符串/函数/布尔/数字,为什么不使用typeof?
jQuery和Underscore都使用这样的东西来检查函数:
Object.prototype.toString.call(obj) == '[object Function]';
Run Code Online (Sandbox Code Playgroud)
这不等于这样吗?
typeof obj === 'function'
Run Code Online (Sandbox Code Playgroud)
甚至这个?
obj instanceof Function
Run Code Online (Sandbox Code Playgroud)
rya*_*nve 16
好吧,我想我弄明白了为什么你会看到这种toString用法.考虑一下:
var toString = Object.prototype.toString;
var strLit = 'example';
var strStr = String('example')?;
var strObj = new String('example');
console.log(typeof strLit); // string
console.log(typeof strStr); // string
console.log(typeof strObj); // object
console.log(strLit instanceof String); // false
console.log(strStr instanceof String); // false
console.log(strObj instanceof String); // true
console.log(toString.call(strLit)); // [object String]
console.log(toString.call(strStr)); // [object String]
console.log(toString.call(strObj)); // [object String]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2315 次 |
| 最近记录: |