Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 545
user2251919 Avatar asked Sep 08 '26 03:09

user2251919


2 Answers

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)

like image 200
Rob W Avatar answered Sep 10 '26 06:09

Rob W


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;
}
like image 21
chtenb Avatar answered Sep 10 '26 06:09

chtenb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!