In JavaScript, for an anonymous function defined inside the object, the this
keyword refers to the object itself. However, when the function is defined outside the object scope, this
refers to the window object, example:
function foo() {
console.log(this)
}
let A = {
att: foo(),
att2: "bla"
}
A.foo();
[EDIT]: I made a mistake in the original code, I meant to call the function as A.att() (and I am obliged to keep att: foo(). My code is basically the following:
function foo() {
console.log(this)
}
let A = {
att: foo(),
att2: "bla"
}
A.att();
The output here is object Window, and not the object that I want to access, which is A. And I can't change A, so how can I access A from foo()?
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 ofthis
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.
To manipulate the this
object by yourself you can use the JS methods call
, apply
& bind
.
Lets demonstrate each with example:
Function.prototype.call()
Detailed info: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
function foo() {
console.log(this)
}
var A = {
att: foo,
att2: "bla"
}
foo.call(A);
Function.prototype.apply()
Detailed info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
function foo() {
console.log(this)
}
var A = {
att: foo,
att2: "bla"
}
foo.apply(A);
Function.prototype.bind()
Detailed info: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
function foo() {
console.log(this)
}
var A = {
att: foo,
att2: "bla"
}
var x = foo.bind(A);
x();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments