0

I have a couple of questions about the "this" keyword use on javascript.


  1. It is true that the constant use of this overloads the entire function object into the RAM memory?
  2. It's better to declare

MyClass = function(){ 
    this.name = "Petter";
    this.age = 12;
    this.toString = function(){
        return "Name: "+this.name + " Age: " + this.age;  
    }
}

instead of


MyClass = function(){
    var _this = this;
    _this.name = "Petter";
    _this.age = 12;
    _this.toString = function(){
        return "Name: "+_this.name + " Age: " + _this.age;  
    }
}

or what can you recommend to me?

YadirHB
  • 168
  • 14
  • [Javascript "this" keyword](http://stackoverflow.com/questions/3127429/javascript-this-keyword) – Andreas Oct 18 '13 at 15:24

3 Answers3

2

No, it's not true, I've never even heard of such a thing.

All you are doing when you do

var _this = this;

Is creating a variable to point to the object in memory that is referred to when you use this. Whether you say:

this.name = "Petter";

or

_this.name = "Petter";

You are still assigning a property to the same object. The way you reference that object (_this or this) makes no difference.

EDIT

You often need to get a reference to this when you want to use this in a different scope (setTimeout's come to mind as a good example).

    var MyClass = function() {
       setTimeout(function() { this.myMethod(); },100);
    };

    MyClass.prototype.myMethod = function() {
      console.log('hi there');
    }

    var myObject = new MyClass();

In the above code, you would get an error because when the setTimeout function gets executed, it does so in the global scope where this === window and you have no function called myMethod() on the window object.

To correct that, you would do this:

    var MyClass = function() {
       var self = this;
       setTimeout(function() { self.myMethod(); },100);
    };

    MyClass.prototype.myMethod = function() {
      console.log('hi there');
    }

    var myObject = new MyClass();

Even though your setTimeout function is executed in the global scope, the variable self actual points to an instance of MyClass (or this) because you did self = this (and because JavaScript is lexically scoped.

Also, and this is just personal preference, you'll quite often see this:

var self = this;

instead of

var _this = this;

Not a big deal, but it's just a convention I thought might be worth mentioning.

Community
  • 1
  • 1
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Or `var me = this` :) – Max Oct 18 '13 at 15:23
  • 1
    Do people do `var self = this;` and `var me = this` because they're accustomed to other languages that actually use `me` or `self` as the keyword rather than `this`? Or is there some other reason? – nhgrif Oct 18 '13 at 15:24
  • @nhgrif Suppose `functionA` is run with some `this`. That function defines some `functionB` that needs to use the `this` from `functionA`. But if `functionB` uses the `this` keyword, it will refer to `functionB`'s *own* `this`. We get around this problem by assigning `functionA`'s `this` to another identifier, asscessible from `functionB`. See [Understanding Javascript scope with “var that = this”](http://stackoverflow.com/questions/12370851/understanding-javascript-scope-with-var-that-this/12371105#12371105) – apsillers Oct 18 '13 at 15:25
  • @nhgrif it's basically down to the fact you can't scope `this`, if you want to, you have to keep the reference as a different variable. i.e. function `A` uses `this`, inside function `A` there is another function defined, `B`. The `this` in `A` is not necessarily the same as the `this` in `B`. Solution: assign `this` to a variable in `A`. **edit** you beat me to it – Paul S. Oct 18 '13 at 15:27
  • I was mainly asking about the naming convention, but thanks. ;) – nhgrif Oct 18 '13 at 15:30
  • If you prefer consistency of the `this` keyword, some Javascript toolkits provide a special method for creating inline functions that are guaranteed a particular object to be 'this'. It's useful when writing small "setTimeout" functions. I know for dojo, it's `dojo.hitch(this, function())`, or `dojo.hitch(this, "nameOfMyFunction")`. There may be a similar function in JQuery. – Katana314 Oct 18 '13 at 15:35
  • @Katana314 - you can do that very easy in vanilla JavaScript using `.bind()` (not supported in IE8), `.call()`, or `.apply()` – Adam Jenkins Oct 18 '13 at 15:37
  • @Adam You learn something new every day! Sounds useful if one could drop IE8 support; call and apply are meant for immediate calling though, rather than saving a function for later. When it's appropriate, I agree I prefer to use those, over mangling a dojo.hitch into an immediate call. – Katana314 Oct 18 '13 at 15:43
0

For the first point it would be in the RAM anyway, I can't say why referencing it with this constantly would change anything.

As for the second point, it is better to store the objects this reference in a variable such as self or _this because in Javascript when you call a function the context of the function can be manipulated by the call and apply functions which will then change what this means.

so with this:

MyClass = function(){ 
    this.name = "Petter";
    this.age = 12;
    this.toString = function(){
        return "Name: "+this.name + " Age: " + this.age;  
    }
}
myObject = new MyClass();
myObject.call({name: 'bob', age: '15'});

The line myObject.call will actually change the reference to this in toString so it will return the "Name: Bob Age: 15" not "Name: Peter Age: 12"

Gabriel Sadaka
  • 1,748
  • 1
  • 15
  • 19
  • 1
    Gabriel, you did hit the nail of my question, because that's an interesting reference. I know how to use this but I wasn't clear about that issue: manipulation of objects. Today I learned something new! – YadirHB Oct 18 '13 at 15:54
0
  1. No, you may be confusing the fact that if you don't use the new keyword when instantiating your objects, you duplicate prototype functions associated with each object instance.

  2. As mentioned in Adam's answer, you are just using more memory by adding another variable. By convention, you will usually see variable names prefixed with an underscore when they are private instance variables.

Community
  • 1
  • 1
Alex W
  • 37,233
  • 13
  • 109
  • 109