JavaScript has a dynamic object named this
. By default, this
equals to the global object container, so if we have a global variable named x
, then this.x === x
. The code below will display the value of x
, which is 10
.
let x = 10;
let print_x = function () {
console.log(this.x);
};
print_x();
Accessing this.x
in a method means accessing attribute x
of the object containing this method. We can use this feature by assigning a JavaScript function to an object attribute. The code below will display a value of 20
.
let print_x = function () {
console.log(this.x);
};
let y = {
'x': 20,
print_x: print_x
};
y.print_x();
You can see that the value of this
in the print_x()
function has changed depending on where it was assigned from. The code below will display a value of 30
.
let z = {
'x': 30,
print_x: print_x
};
z.print_x();
If desired, so that the value of this
does not change whenever print_x()
function is reassigned, other techniques are required.
See the bind()
function below:
Function.prototype.bind = function () (
let fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () (
return fn.apply(object, args.concat (Array.prototype.slice.call(arguments)));
);
);
Now the code below will still display the value of 20
despite what being called is z.print_x
:
let y = {
'x': 20
};
print_x = print_x.bind(y);
let z = {
'x': 30,
print_x: print_x
};
z.print_x();