Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

closure can use new keyword and what is difference for instance, when creating a new object/class

Tags:

javascript

I am new and going on javascript way. At the point of Closure. I can create object with new keyword and without new keyword, it is so weird me.

Here code:-

          function RankingManage(rank) {
                var rank = rank;
                function rankInc() {
                    rank++;
                }
                function rankDec() {
                    rank--;
                }

                return {
                    makeInc: function () {
                        rankInc();
                    },
                    makeDec: function () {
                        rankDec();
                    },
                    showRank: function () {
                        return rank;
                    }
                }
            }

            var Rank = new RankingManage(80);
            var Rank2 = RankingManage(80);
            Rank.makeInc();
            Rank2.makeInc();
            console.log(Rank.showRank());//Output:- 81
            console.log(Rank2.showRank());//Output:- 81
like image 343
vineet Avatar asked Jan 07 '23 21:01

vineet


2 Answers

This has nothing to do with closures.

Using new sets the value of this for the function to a new object and causes it to return this by default.

You are using a return statement to explicitly return an object, so you return that object instead of this.

like image 66
Quentin Avatar answered Jan 09 '23 10:01

Quentin


Because you're creating and returning an object (with the return { ... }), you wouldn't normally call RankingManage via new. You're not using the object that the new operator creates, and you're overriding the default result of the new expression by returning a non-null object from the function. So both ways work, but it doesn't make sense to use new with your function as currently written.

Your current function is absolutely fine, just call it wihtout new. (And since it's not a constructor function — a function you call with new — you'd start it with a lower-case letter, by convention, not an upper-case one. So rankingManage.)

If you wanted to require new when calling RankingManage, you could use the object that new creates via the this keyword:

function RankingManage(rank) {
    var rank = rank;

    function rankInc() {
        rank++;
    }

    function rankDec() {
        rank--;
    }

    this.makeInc = rankInc;
    this.makeDec = rankDec;
    this.showRank = function() {
        return rank;
    };
}

We don't use a return in that, because (again) the default result of the new RankingManage expression is a reference to the object that new created.

But again, your existing function is fine.

like image 30
T.J. Crowder Avatar answered Jan 09 '23 11:01

T.J. Crowder