this, apply, call and bind

What this represents

this means where the current property is from.

What this points to

this points to the object which is the last to calls it.

1
2
3
4
5
6
7
8
9
10
var name = "windowsName";
function a() {
var name = "Cherry";

console.log(this.name); // windowsName

console.log("inner:" + this); // inner: Window
}
a();//window.a()
console.log("outer:" + this) // outer: Window
1
2
3
4
5
6
7
8
var name = "windowsName";
var a = {
name: "Cherry",
fn : function () {
console.log(this.name); // Cherry
}
}
a.fn();
1
2
3
4
5
6
7
8
9
10
11
var name = "windowsName";
var a = {
name : null,
// name: "Cherry",
fn : function () {
console.log(this.name); // windowsName
}
}

var f = a.fn;
f();
1
2
3
4
5
6
7
8
9
10
11
var name = "windowsName";

function fn() {
var name = 'Cherry';
innerFunction();
function innerFunction() {
console.log(this.name); // windowsName
}
}

fn()

Methods to change where this points

Arrow Function

this in arrow function points where the function is defined, instead of conducting.

If there is no this in arrow function, we must find the scope chain to find the value. if a non-arrow function contains the arrow function, this in the arrow function is the this in the non-arrow function, otherwise this is undefined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var name = "windowsName";

var a = {
name : "Cherry",

func1: function () {
console.log(this.name)
},

func2: function () {
setTimeout( () => {
this.func1()
},100);
}

};

a.func2() // Cherry

_this = this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var name = "windowsName";

var a = {

name : "Cherry",

func1: function () {
console.log(this.name)
},

func2: function () {
var _this = this;
setTimeout( function() {
_this.func1()
},100);
}

};

a.func2() // Cherry

apply, call, bind

apply & call difference:

1
2
3
fun.apply(thisArg, [argsArray])
fun.call(thisArg[, arg1[, arg2[, ...]]])
fun.bind(thisArg[, arg1[, arg2[, ...]]])()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var a = {
name : "Cherry",

func1: function () {
console.log(this.name)
},

func2: function () {
setTimeout( function () {
this.func1()
}.apply(a),100);
}

};

a.func2() // Cherry