Closing can use a new keyword and what is the difference, for example, when creating a new object / class

I am new and switching to javascript. At the point of closure . I can create an object with a keyword newand without a keyword new, so it's weird .

Here's the 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
+4
source share
4 answers

( return { ... }), RankingManage new. , new, new, non null . , , new , .

, wihtout new. ( - — , new — , , . RankingManage. )

new RankingManage, , new this:

function RankingManage(rank) {
    var rank = rank;

    function rankInc() {
        rank++;
    }

    function rankDec() {
        rank--;
    }

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

return , () new RankingManage , new.

.

+2

.

new this this .

return , this.

+4

, -, .

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"

, new window .

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

+1

, :

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

, new (new Car('red');), :

  • this , .
  • . ( , this ).

  • This empty object will be filled with properties: wheelsand color.

  • Implicitly returns this object. (If you have an explicit statement return, this object thiswill be discarded.)

At the end, your returned object has the following structure:

{
    wheels: 4,
    color: 'red'
}
+1
source

Source: https://habr.com/ru/post/1622515/


All Articles