Analysis of common situations of JavaScript this keyword pointing
- 2021-08-10 06:36:25
- OfStack
In the previous experience of writing code, I often try to write this, and I don't know where to point. Today, I looked at the javascript design pattern I explored, which specifically talked about the objects that this refers to in different situations, which is very interesting.
The situation referred to by this
this has the following four situations:
1. Object. Formal call of function: object. function ();
2. Formal call of ordinary function: function ();
3. Constructor call;
4. Function. prototype. call or Function. prototype. apply call;
1. Object. Formal call of function
Object. When called as a function, refers to this object.
var obj = {
num:1,
getNum:function(){
alert(this.num);// Output 1
}
}
obj.getNum();
2. Call in the form of ordinary function
When a normal function is called, this points to a global object.
window.num = 2;
var obj = {
num:1,
getNum:function(){
alert(this.num);
}
}
obj.getNum();// Eject 1
var fun1 = obj.getNum;
fun1(); // Eject 2
Amazing, call the function fun () directly; Calling functions xxx. fun () through objects; this refers to different objects.
3. Constructor call
In order to use the new keyword, the creation object of javascript can be defined as follows.
var person = function(){
this. name = 'Liu Bei';
}
In this case, this refers to the object being created.
var p = new person();
alert (p. name); //Eject Liu Bei
4. Function. prototype. call or Function. prototype. apply call
var obj1 = {
name:' Guan Yu ',
getName:function(){
return this.name;
}
}
var obj2 = {
name:' Liu Bei '
}
alert(obj1.getName()); // Guan Yu
alert(obj1.getName.call(obj2)); // Liu Bei