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.
What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called).
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.
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.
“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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With