开发者

explicit typeof == "undefined" check vs just checking for its existence?

开发者 https://www.devze.com 2023-03-03 20:05 出处:网络
assuming x is an object...Is there any benefit of doing: if (typeof x.foo != \"undefined\") vs. doing if (x.foo)

assuming x is an object... Is there any benefit of doing:

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

vs. doing

 if (x.foo)

?

This question came up as I was reading this blog post: http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

In his example, he does:

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);

In this case this._listeners[type] will never be anything except an array-- so is it not true tha开发者_如何学Got it would be cleaner in this case to just do

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

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

?

Also, as a side question, I don't get why he's doing:

EventTarget.prototype = {

  constructor: EventTarget

Isn't the constructor by default already set to EventTarget ('this') when you call new EventTarget() ?


Watch out for truthy values.

if (x.foo) will not run if x.foo is

  • false
  • null
  • undefined
  • ""
  • 0
  • NaN

Where as if (typeof x.foo !== "undefined") { only checks for whether the value is undefined

Alternative checks would be

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

Do be wary that undefined can be overwritten as a local variable

undefined = true is a valid statement and will break all your code. Of course you will never see this code in production so you don't really have to shield against it, it's just something to be wary of.

I personally tend to use

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

a lot which checks for both null and undefined.

[[Edit]]

In your specific example it's either an Array or undefined so !foo is safe. personally I prefer to check specifically for undefined so that users know I only expect it to run when it's undefined rather then when it's null or false or "". This makes the code more explicit / self documenting.

As to

EventTarget.prototype = {

  constructor: EventTarget

If you overwrite EventTarget.prototype with a new object then the EventTarget.prototype.constructor property is lost and needs to be set again.

You do not need to set .constructor again if you just extend the prototype by calling EventTarget.prototype.method = ....


The first explicitly checks that x.foo is undefined, whereas if (x.foo) is checking to see if x.foo is truthy.

http://11heavens.com/falsy-and-truthy-in-javascript

0

精彩评论

暂无评论...
验证码 换一张
取 消