Javascript static vs instance, prototype keyword

前端 未结 2 1248
春和景丽
春和景丽 2020-12-17 17:40

I want to know the difference between the following two code snippets

What I understand is this is static because without creating an instance with new keyword, getC

2条回答
  •  臣服心动
    2020-12-17 18:16

    Further details

    @jfriend00 has already given a very helpful details on how JavaScript treats object. Let me add some details about the difference of this keywords in both cases:

    Static case

    If you define a static function through an object's property, the this keyword in the function refers to function scope, not the parent object.

    See example:

    var F = function(){ this.a = 500; };
    F.G = function(){ return this.a; };
    
    // call it
    F.G(); // returns undefined, because `this` refers to F.G()
           // but the variable a in F.G() has not been defined yet
    

    Prototype case

    If you define a function through object's prototype, the this keyword in the function refers to the instance of object you create from that prototype, not the function scope.

    See example:

    var F = function(){ this.a = 500; };
    F.prototype.G = function(){ return this.a };
    
    // Make an object and call the function
    var f = new F();
    f.G(); // returns 500 because `this` refers to instance f 
    

提交回复
热议问题