I have a constructor function which registers an event handler:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);
However, I'm not able to access the data
property of the created object inside the callback. It looks like this
does not refer to the object that was created but to an other one.
I also tried to use an object method instead of an anonymous function:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
but it exhibits the same problems.
How can I access the correct object?
Currently there is another approach possible if classes are used in code.
With support of class fields it's possible to make it next way:
For sure under the hood it's all old good arrow function that bind context but in this form it looks much more clear that explicit binding.
Since it's Stage 3 Proposal you will need babel and appropriate babel plugin to process it as for now(08/2018).
The question revolves around how
this
keyword behaves in javascript.this
behaves differently as below,this
is usually determined by a functions execution context.this
refers to the global object (thewindow
object).this
will beundefined
as in strict mode, global object refers toundefined
in place of thewindow
object.call()
,bind()
, andapply()
new
keyword is used (a constructor), this is bound to the new object being created.this
— instead,this
is bound lexically (i.e. based on the original context)As most of the answers suggest, we can use Arrow function or
bind()
Method or Self var. I would quote a point about lambdas (Arrow function) from Google JavaScript Style GuideGoogle clearly recommends to use lambdas rather than bind or
const self = this
So the best solution would be to use lambdas as below,
References:
Another approach, which is the standard way since DOM2 to bind
this
within the event listener, that let you always remove the listener (among other benefits), is thehandleEvent(evt)
method from theEventListener
interface:Detailed information about using
handleEvent
can be found here: https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38The trouble with "context"
The term "context" is sometimes used to refer to the object referenced by this. Its use is inappropriate because it doesn't fit either semantically or technically with ECMAScript's this.
"Context" means the circumstances surrounding something that adds meaning, or some preceding and following information that gives extra meaning. The term "context" is used in ECMAScript to refer to execution context, which is all the parameters, scope and this within the scope of some executing code.
This is shown in ECMA-262 section 10.4.2:
which clearly indicates that this is part of an execution context.
An execution context provides the surrounding information that adds meaning to code that is being executed. It includes much more information than just the thisBinding.
So the value of this isn't "context", it's just one part of an execution context. It's essentially a local variable that can be set by the call to any object and in strict mode, to any value at all.
First, you need to have a clear understanding of
scope
and behaviour ofthis
keyword in the context ofscope
.this
&scope
:in short, global scope refers to the window object.Variables declared in a global scope are accessible from anywhere.On the other hand function scope resides inside of a function.variable declared inside a function cannot be accessed from outside world normally.
this
keyword in global scope refers to the window object.this
inside function also refers to the window object.Sothis
will always refer to the window until we find a way to manipulatethis
to indicate a context of our own choosing.Different ways to manipulate
this
inside callback functions:Here I have a constructor function called Person. It has a property called
name
and four method calledsayNameVersion1
,sayNameVersion2
,sayNameVersion3
,sayNameVersion4
. All four of them has one specific task.Accept a callback and invoke it.The callback has a specific task which is to log the name property of an instance of Person constructor function.Now let's create an instance from person constructor and invoke different versions of
sayNameVersionX
( X refers to 1,2,3,4 ) method withniceCallback
to see how many ways we can manipulate thethis
inside callback to refer to theperson
instance.bind :
What bind do is to create a new function with the
this
keyword set to the provided value.sayNameVersion1
andsayNameVersion2
use bind to manipulatethis
of the callback function.first one bind
this
with callback inside the method itself.And for the second one callback is passed with the object bound to it.call :
The
first argument
of thecall
method is used asthis
inside the function that is invoked withcall
attached to it.sayNameVersion3
usescall
to manipulate thethis
to refer to the person object that we created, instead of the window object.and it is called like the following :
apply :
Similar to
call
, first argument ofapply
refers to the object that will be indicated bythis
keyword.sayNameVersion4
usesapply
to manipulatethis
to refer to person objectand it is called like the following.Simply the callback is passed,
You Should know about "this" Keyword.
As per my view you can implement "this" in three ways (Self/Arrow function/Bind Method)
A function's this keyword behaves a little differently in JavaScript compared to other languages.
It also has some differences between strict mode and non-strict mode.
In most cases, the value of this is determined by how a function is called.
It can't be set by assignment during execution, and it may be different each time the function is called.
ES5 introduced the bind() method to set the value of a function's this regardless of how it's called,
and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).
Method1: Self - Self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Method2: Arrow function - An arrow function expression is a syntactically compact alternative to a regular function expression,
although without its own bindings to the this, arguments, super, or new.target keywords.
Arrow function expressions are ill suited as methods, and they cannot be used as constructors.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Method3:Bind- The bind() method creates a new function that,
when called, has its this keyword set to the provided value,
with a given sequence of arguments preceding any provided when the new function is called.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind