2

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't this method require that you know inside the function what context it's being called in?
@sam Not sure I understand. The if statement determines the context.
I suppose it works if you create it as var obj = - however, if you declare it as a named function, you won't be able to use that comparison; eg. function obj() {}
The first example works perfectly inside a function declaration.
2

The instanceof operator can be utilized for another solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.