4

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
vineet
  • 10,659
  • 9
  • 50
  • 69
  • 1
    This might answer your question: http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript/3658673#3658673 – m0meni Jan 02 '16 at 11:19
  • Possible duplicate of [creating objects from JS closure: should i use the "new" keyword?](http://stackoverflow.com/questions/9304473/creating-objects-from-js-closure-should-i-use-the-new-keyword) – Zakaria Acharki Jan 02 '16 at 11:19
  • The closure here is letting you define variables and functions without them entering the global namespace. The `new` here does nothing useful as as `RankingManage` is returning an _Object_ – Paul S. Jan 02 '16 at 11:37
  • when you use return in closure with obj syntax `{}` it already creates a new object for you, no point of using `new` again. makes sense now? – super cool Apr 23 '20 at 06:16

4 Answers4

5

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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
2

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.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
1

Usually, things are done a little bit differently when you're defining an object in this way.

public function MyObject(value) {
    this.value = value;
    this.doSomething = function() { console.log("Hello!"); };
}

var myObject = new MyObject(10);
var notObject = MyObject(10);

myObject.doSomething(); // Prints Hello!
notObject.doSomething(); // Prints out "can not get property of undefined"

You will now see a change in behaviour, because new prevents the default behaviour of adding values to window and adds them to an object that gets returned.

JSFiddle: https://jsfiddle.net/LLx3376n/

christopher
  • 24,892
  • 3
  • 50
  • 86
1

Suppose we've the following function:

function Car(color){
    this.wheels = 4;
    this.color = color;
}

What exactly new operator does (new Car('red');) could be stated as follows:

  • Create an empty object and make the this inside the function to point to.
  • Invoke the function. (Note that this points to that empty object).

  • That empty object will be populated with properties: wheels and color.

  • Implicitly returns that object. (If you have explicit return statement, that object of this will be discarded.)

At the end, your returned object is of this structure:

{
    wheels: 4,
    color: 'red'
}
frogatto
  • 26,401
  • 10
  • 73
  • 111