2011-05-09 51 views
5

假设x是一个对象...有没有这样做的任何好处:显式typeof ==“未定义”检查vs只是检查其存在?

if (typeof x.foo != "undefined") 

与做

if (x.foo) 

这个问题上来,因为我正在读这篇博客文章: http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

在他的榜样,他的作用:

function EventTarget(){ 
    this._listeners = {}; 
} 

EventTarget.prototype = { 

    constructor: EventTarget, 

    addListener: function(type, listener){ 
    if (typeof this._listeners[type] == "undefined"){ 
     this._listeners[type] = []; 
    } 

    this._listeners[type].push(listener); 

在这种情况下this._listeners【类型】绝不会只是什么一个array--所以是不正确的,这将是清洁在这种情况下只是做

addListener: function(type, listener){ 
    if (!this._listeners[type]){ 
     this._listeners[type] = []; 
    } 

    this._listeners[type].push(listener); 

此外,作为一个侧面的问题,我不知道为什么他在做:

EventTarget.prototype = { 

    constructor: EventTarget 

不是默认的构造已设置为事件目标(“本”),当你调用新的EventTarget() ?

+0

还有第三种选择:'如果(x.foo ==未定义!)'。注意* double = *(没有类型强制的平等) – 2011-05-09 19:45:39

+1

@Dan:虽然如果一些傻瓜改变'未定义',那会中断。是的,这是可能的。 – delnan 2011-05-09 19:50:46

+0

@delnan真的,但有些方法可以防范:'(function(undefined){... undefined在这里真的没有定义...}())' – 2011-05-09 19:53:14

回答

10

小心truthy values。如果x.foo是

  • if (x.foo)将无法​​运行

  • 不确定
  • “”
  • NaN的

凡为if (typeof x.foo !== "undefined") {个对值是否undefined

替代检查检查是

if (x.foo !== undefined) {if (x.foo !== void 0) {

做提防undefined可以覆盖一个局部变量

undefined = true是一个有效的声明,会破坏你的所有代码。当然,你永远不会看到这个代码在生产中,所以你不必屏蔽它,它只是需要谨慎的东西。

我个人倾向于使用

if (x.foo != null) { 
    ... 
} 

很多,检查两个nullundefined

[编辑]

在您的具体实例它要么一个Arrayundefined所以!foo是安全的。我个人更喜欢专门检查undefined,以便用户知道我只希望它在未定义时运行,而不是在nullfalse""时运行。这使代码更加明确/自我记录。

至于

EventTarget.prototype = { 

    constructor: EventTarget 

如果覆盖EventTarget.prototype一个新的对象,然后将EventTarget.prototype.constructor财产发生丢失,需要重新设置。

如果您只是通过调用EventTarget.prototype.method = ...来扩展原型,则不需要再设置.constructor

+0

我更新了我的问题,以回应你写的内容... – patrick 2011-05-09 21:47:28

+0

@patrick解决。 – Raynos 2011-05-09 21:54:07

+0

明白了。非常感谢您的信息! – patrick 2011-05-10 04:40:14