Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript this object

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.

like image 620
Tejesh Alimilli Avatar asked Apr 16 '12 14:04

Tejesh Alimilli


People also ask

What is this object in JavaScript?

What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called).

Does JavaScript have this?

In JavaScript, the this keyword allows us to: Reuse functions in different execution contexts. It means, a function once defined can be invoked for different objects using the this keyword.

What does '$' mean in JavaScript?

Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

Why do we use this in JavaScript?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.


1 Answers

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
like image 171
JaredPar Avatar answered Sep 30 '22 21:09

JaredPar