javascript 中的类型并不那么简单,但this 是您的绝佳指南!
在 Javascript 中检查类型是一团糟。
类型运算符
一开始有typeof。这个方便的运算符为您提供
Javascript 值的“类型”:
typeof 3 // "number"
typeof "abc" // "string"
typeof {} // "object"
typeof true // "boolean"
typeof undefined // "undefined"
typeof function(){} // "function"
一切都很好,直到
typeof [] // "object"
嗯?数组的类型是对象?我想是的,如果你想得到
关于它的技术,但仍然是……
typeof null // "object"
好吧,那就错了!
instanceof 运算符
instanceof 操作符告诉你一个对象是否
是某种类型的实例。所谓“型”是
构造函数。例如
function Animal(){}
var a = new Animal()
a instanceof Animal // true
instanceof的跨窗口问题
原来instanceof还有一个问题。它崩溃时
您尝试测试来自另一个窗口的对象。你懂的?这
为每个创建的,或弹出窗口
你创造。
var iframe = document.createElement('iframe')
document.body.appendChild(iframe)
var iWindow = iframe.contentWindow // get a reference to the window object of the iframe
iWindow.document.write('<script>var arr = [1, 2, 3]</script>') // create an array var in iframe's window
iWindow.arr // [1, 2, 3]
iWindow.arr instanceof Array // false
鸭式打字
因为 typeof 和 instanceof 都不能令人满意,所以很多人使用
鸭子打字。这意味着检查行为:如果它看起来像鸭子
和鸭子一样嘎嘎叫,那么就我而言,它是一只鸭子。
很确定我引用错了……哦,好吧。
因此,使用鸭子类型,isArray 检查可能看起来像
// source: http://forums.devshed.com/javascript-development-115/javascript-test-whether-a-variable-is-array-or-not-33051.html
function isArray(obj){
return (typeof(obj.length)=="undefined") ?
false:true;
}
Object.prototype.toString 方法
事实证明,您可以通过以下方式获取有关对象的类型信息
使用 Object.prototype.toString 方法。
Object.prototype.toString.call(3) // "[object Number]"
Object.prototype.toString.call([1, 2, 3]) // "[object Array]"
Object.prototype.toString.call({}) // "[object Object]"
Function.prototype.toString 方法
另一种测试类型信息的方法是使用
Function.prototype.toString 方法。
Function.prototype.toString.call((3).constructor)
// "function Number() {
// [native code]
// }"
DOM 元素和宿主对象
到目前为止,我还没有提到 DOM 元素和宿主的类型检查
对象。那是因为它很难。除了打鸭子,
上述方法均不适用于所有浏览器。如果你
掉IE7及以下,但是,你实际上可以得到一些东西
去工作。下面的输出是使用 Tutti 创建的
var div = document.createElement('div')
typeof div
Safari 5.0 => object
Firefox 3.6 => object
IE 7.0 => object
IE 8.0 => object
Opera 11.01 => object
div instanceof Element
Safari 5.0 => true
Firefox 3.6 => true
IE 7.0 => Error: 'Element' is undefined
IE 8.0 => true
Opera 11.01 => true
div instanceof HTMLDivElement
Safari 5.0 => true
Firefox 3.6 => true
IE 8.0 => true
IE 7.0 => Error: 'HTMLDivElement' is undefined
Opera 11.01 => true
http://tobyho.com/2011/01/28/checking-types-in-javascript/