Short answer: invoke the function via call
and pass the intended this
as the first argument.
function test(value) {
this.prop = value
}
// 'this' v v value
test.call(test, 10)
console.log(test.prop) // 10
The purpose of call
is to explicitly set the this
of the invoked function.
Explanation:
For non-strict mode, when the function is invoked without a caller, e.g., test(10)
, this
is implicitly set to the global object, in this case window
. In strict mode, it will be undefined
.
function test() {
return this
}
console.log(test()) // window (or undefined in strict mode)
Inside of a function, this
refers to the caller of the function.
const caller = {
test: function () { return this }
}
console.log(caller.test()) // caller, i.e., { test: function() {...} }
This is true with 'classes' as well (functions invoked with new
).
function MyConstructor() {
this.test = function() {
return this
}
}
const instance = new MyConstructor()
console.log(instance.test()) // instance of MyConstructor
Depending on your use case, it may be preferable to use this form:
const myObj = {
test: function(value) {
this.prop = value
}
}
// 'prop' will be set on `myObj` instead of the function.
myObj.test(10)
console.log(myObj) // { prop: 10, test: function(value) {...} }
or a class-like construct:
function MyConstructor(value) {
this.prop = value
}
const instance = new MyConstructor(10)
console.log(instance) // MyConstructor { prop: 10 }
console.log(instance.prop) // 10