javascript this object

javascript, this

Solution

While this is a common practice in Javascript it's not done for performance reasons. The saving of the `this` object in another named local is usually done to preserve the value of `this` across callbacks which are defined within the function.

function someFunction() {
  var thisObject = this;
  var someCallback = function() {
    console.log(thisObject === this);  // Could print true or false
  };
  return someCallback;
}

Whether or not `thisObject === this` evaluates to true will depend on how it's called

var o = {} 
o.someFunction = someFunction();
var callback = o.someFunction();
callback();        // prints false
callback.call(o);  // prints true

Problem

I have been working on web project for past 4 months. To optimise the code performance we have used a pattern. My doubt is, does it actually boost performance or not? when ever we have to use `this` object we assign it to a local variable, and use that. ``` function someFunction() { var thisObject = this; //use thisObject in all following the code. } ``` the assumption here is that, assigning `this` object to a local stack variable will boost the performance. I have not seen this type of coding anywhere so doubt if it is of no use. EDIT: I know that assigning this object to local variable is done for preserving object, but that is not our case.

Original source

Related problems