user2251919
user2251919

Reputation: 675

Returning an object but not using the new keyword, Javascript?

I am trying to create an object that gets returned without the new keyword in javascript?

My code structure so far;

myLib.func = (function() {

    "use strict";

    function func() {

        this._init();
    };

    func.prototype._init = function() {

        this.someVar = 5;
    };

    Return func;

})();

This obviously only works when using the new keyword;

new myLib.func();

How can I make it so that I can just do;

var func = myLib.func();

But it would still return an object that is exactly the same as the first example?

What I have tried

myLib.func = (function() {

    "use strict";

    function func() {

        if (window === this) {
            return new myLib.func();
        } else {
            this._init();
        }
    };

    func.prototype._init = function() {

        this.someVar = 5;
    };

    Return func;

})();

This does not work I learned from an example on slide 25 of John Resig's tips on building a library, http://ejohn.org/blog/building-a-javascript-library/

I know there are already existing frameworks, but rolling my own will make me learn alot, and as you can see that isn't alot at the moment!

Upvotes: 3

Views: 88

Answers (3)

Rob W
Rob W

Reputation: 348992

In strict mode, the this will be undefined by default. You can account for this feature by adding it to your condition:

    if (window === this || undefined === this) {
        return new myLib.func();
    } else {
        this._init();
    }

or by checking whether the current object is an instance of the constructor (using instanceof):

    if (this instanceof func) {
        this._init();
    } else {
        return new func();
    }

(PS. You've got a typo in your code; JavaScript is case-sensitive, so you should use return instead of Return at the end)

Upvotes: 2

Draykos
Draykos

Reputation: 822

If you don't really need public / private methods, you can use object literal

var myLib = {}; 
myLib.func = {
     _init: function() {
         this.someVar = 5;
     },
     doSomething: function(a, b) {
        return a + b;
     }
};

This will be a singleton object, usually it's enough for javascript applciation. If you need many instances of an object, you'll be forced to put a "new" keyword somewhere.

Upvotes: 0

chtenb
chtenb

Reputation: 16184

If myLib.func is your class name, you cannot call it like var func = myLib.func();. However, you could wrap this latter into another function, such that you get

var factory = function(){
    var func = myLib.func();
    return func;
}

Upvotes: 1

Related Questions