Patrick Lorio
Patrick Lorio

Reputation: 5668

JavaScript is Object or Function

I have this code:

var obj = function (i) {
   this.a = i;
   this.init = function () {
       var _this = this;
       setTimeout(function () {
           alert(_this.a + ' :: ' + typeof _this);
       }, 0);
   };
   this.init();
};

obj('1');
obj('2');
obj('3');
new obj('4');​​​

http://jsfiddle.net/kbWJd/

The script alerts '3 :: object' three times and '4 :: object' once.

I know why this is. It because new obj('4') creates a new instance with it's own memory space and the calls prior share their memory space. When in the code of obj how can I determine if I am a new object or a function, since typeof _this just says 'object'?

Thanks.

Upvotes: 2

Views: 2153

Answers (2)

Niko
Niko

Reputation: 26730

The instanceof operator can be utilized for another solution:

var foo = function() {
    if (this instanceof foo) {
        // new operator has been used (most likely)
    } else {
        // ...
    }
};

Upvotes: 2

Bryan Downing
Bryan Downing

Reputation: 15472

Is this what you're looking for? If you execute a function without the new keyword this inside the function equals the containing object (window in this case).

if( this === window ){
    console.log('not an object instance');
} else {
    console.log('object instance');
}

Example with different containing object:

var obj = {

    method: function(){

        if( this === obj ){
            alert('function was not used to create an object instance');
        } else {
            alert('function was used to create an object instance');
        }

    }

};


obj.method(); // this === obj

new obj.method(); // this === newly created object instance

Upvotes: 2

Related Questions