const obj = {
name: "sri1",
func1: function() { // <-- 1
const name = "sri2"
function a() { // <-- 2
console.log(this.name)
}
a();
}
}
Normally this
points to the window
object of the browser.
But inside an object, if we define a property with an anonymous function then the this
points to the object itself. But another function inside the function? No, it points to the window
object.
So, for your example. I've marked your code with two reference points by comments.
- Mark 1 function, it's the function of the object's property. So
this
points to the obj
object.
- Mark 2 function, it's inside the mark 1 function so now,
this
inside the function a()
points to the window
object. (If you don't believe me then check it by using console.log(this)
inside the function a()
)
How can I get the object's this
inside the inner function?
There are several ways to achieve this. I am mentioning few of them.
Using arrow function
.
An arrow function doesn't alter the reference of this
pointer. It points to the blocks this
in which block the function lays.
const obj = {
name: "sri1",
func1: function() {
const name = "sri2"
const a = () => { // Using arrow function
console.log(this.name)
}
a();
}
}
Keep the previous this
into a variable.
You can put the this
into a variable say, that
, then access the value using that.name
.
const obj = {
name: "sri1",
func1: function() {
const name = "sri2"
const that = this; // Put this into that
function a() {
console.log(that.name); // Access the name using that.name
}
a();
}
}
Bind this
when you call the function.
You can bind the this
with the function to use inside it.
const obj = {
name: "sri1",
func1: function() {
const name = "sri2"
function a() {
console.log(this.name)
}
const withThis = a.bind(this); // Make a function reference with `this` bindings
withThis(); // Call the function
}
}
Using call()
or apply()
The call()
method calls a function with a given this value and arguments provided >individually.
While the syntax of this function is almost identical to that of
apply()
, the fundamental difference is that call()
accepts an argument
list, while apply()
accepts a single array of arguments.
const obj = {
name: "sri1",
func1: function() {
const name = "sri2"
function a() {
console.log(this.name)
}
a.call(this); // call() binds the `this`
// Or
a.apply(this); // apply() also binds the `this`
}
}