细说 Javascript 范例篇(二) : typeof 操作符

typeof 操作符(另有 instanceof)多是 Javascript 设想中最大缺点,因为它几乎是完整破坏的。因为 typeof 用法与挪用函数的语法类似,因而常被误以为是函数挪用,现实上并不存在名为 typeof 的函数,typeof 只是一个操作符罢了。
只管 instanceof 依然另有少数的运用场景,typeof 则只要一个现实的用途,但这个用途不能用来检测对象的范例。

范例表格

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object (function in Nitro/V8)
new RegExp("meow")  RegExp     object (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object

在上述表格中,Type 列示意 typeof 操作符的效果。而 Class 列则示意对象内部的 [[Class]] 属性。
为了取得 [[Class]] 属性,我们须要运用 Object.prototypetoString 要领。

Class 属性

文档中明确地给出了取得 [[Class]] 属性的门路,就是运用 Object.prototype.toString

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test'); // true
is('String', new String('test')); // true

上例中,Object.prototype.toString 被挪用,this 被设置指向须要获取其 [[Class]] 属性值的对象。

文档定义: [[Class]] 属性的值只多是以下字符串: Arguments, Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, String
nullundefined 挪用 Object.prototype.toString 要领时, 其返回值将由 Object 变成了 NullUndefined

测试变量是不是定义

typeof foo !== 'undefined'

上述语句将会测试变量 foo 已定义与否,假如未定义而援用 foo 将会抛出 ReferenceError 毛病,这现实上是 typeof 用途最大的处所。

总结

为了检测一个对象的范例,最牢靠的要领就是运用 Object.prototype.toString,正如第一个表格上的内容,typeof 操作符并不能返回确实的对象范例,然则我们能够运用 typeof 操作符常常会被用来推断变量是不是定义。
实在 typeof 操作符还能够被用来测试变量是不是为函数,@humphry 先辈的回复进一步雄厚了 typeof 的用途:

《怎样准确推断js数据范例》

参考

http://bonsaiden.github.io/JavaScript-Garden/#types.typeof

    原文作者:StephenLee
    原文地址: https://segmentfault.com/a/1190000000504967
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞