Explicit typeof == "undefined" check vs just checking its existence?

Assuming x is an object ... Are there any advantages:

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

against. do

 if (x.foo)

?

This question arose as I read this blog post: http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

In his example, he:

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 but an array - is that not true, which in this case would be simpler to 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 understand why it does:

EventTarget.prototype = {

  constructor: EventTarget

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

+5
source share
2 answers

.

if (x.foo) , x.foo

  • NULL
  • undefined
  • ""
  • 0
  • NaN

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

:

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

, undefined

undefined = true . , , , , .

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

null, undefined.

[[Edit]]

Array, undefined, !foo . undefined, , , , undefined, null false "". / .

EventTarget.prototype = {

  constructor: EventTarget

EventTarget.prototype , EventTarget.prototype.constructor .

.constructor, , EventTarget.prototype.method = ....

+10

, x.foo undefined, if (x.foo) , x.foo .

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

+2

All Articles