[removed] Do I need to put this.var for every variable in an object?

前端 未结 6 1323
太阳男子
太阳男子 2020-11-21 05:06

In C++, the language I\'m most comfortable with, usually one declares an object like this:

class foo
{
public:
    int bar;
    int getBar() { return bar; }
         


        
6条回答
  •  执笔经年
    2020-11-21 05:57

    function Foo() {
      this.bar = 0;
      this.getBar = function () { return this.bar };
    }
    

    When you call the function above with the new keyword - like this...

    var foo = new Foo();
    

    ... - a few things happen:

    1) an object is created
    2) the function is executed with the this keyword referencing that object.
    3) that object is returned.

    foo, then, becomes this object:

    {
        bar: 0,
        getBar: function () { return this.bar; }
    };
    

    Why not, then, just do this:

    var foo = {
        bar: 0,
        getBar: function () { return this.bar; }
    };
    

    You would, if it's just that one simple object.

    But creating an object with a constructor (that's how it's called) gives us a big advantage in creating multiple of the "same" objects.

    See, in javascript, all functions are created with a prototype property [an object], and all objects created with that function (by calling it with the new keyword) are linked to that prototype object. This is why it's so cool - you can store all common methods (and properties, if you wanted to) in the prototype object, and save a lot of memory. This is how it works:

    function Foo( bar, bob ) {
       this.bar = bar;
       this.bob = bob;
    }
    
    Foo.prototype.calculate = function () {
      // 'this' points not to the 'prototype' object 
      // as you could've expect, but to the objects
      // created by calling Foo with the new keyword.
      // This is what makes it work.
      return this.bar - this.bob;  
    };
    
    var foo1 = new Foo(9, 5);
    var foo2 = new Foo(13, 3);
    var result1 = foo1.calculate();
    var result2 = foo2.calculate();
    
    console.log(result1); //logs 4
    console.log(result2); //logs 10
    

    That's it!

提交回复
热议问题