Reputation:
We have this kind of situation where we need to bind a nested function within an object to the object itself. when we try to bind the function to this
it is being binded to the window instead...
var a = {
b: [{
onclick: function() {
console.log(this)
}.bind(this)
}]
}
a.b[0].onclick() // this = window
Is there any possible way of biding the scope of b[0].onclick
to object a
without have to use call
and apply
when calling the function?
Thanks!
Upvotes: 1
Views: 1142
Reputation: 7146
You can do it in 2 steps. First, create the object, then add the methods that you bind to it :
const a = {};
a.b = [{
onclick: function() {
console.log(this)
}.bind(a)
}];
a.b[0].onclick();
Upvotes: 0
Reputation: 92460
You can make b
a getter rather than a direct reference to an array. This will allow you to use lexical binding and an arrow function to access a
as this
. Callers should be none the wiser:
var a = {
name: "My Name",
get b() {
return [{
onclick: () => {
console.log("this name:", this.name)
}
}]
}
}
a.b[0].onclick() // this = a
Upvotes: 1
Reputation: 371019
After a
has been declared, bind
the onclick to a
, once, and then every time the onclick is invoked, the calling context will be a
:
var a = {
b: [{
onclick: function() {
console.log(this)
}
}]
};
a.b[0].onclick = a.b[0].onclick.bind(a);
a.b[0].onclick()
You can also define the function after declaring a
:
var a = {
b: [{
}]
};
a.b[0].onclick = function() {
console.log(this);
}.bind(a);
a.b[0].onclick()
Upvotes: 2