This point in JS must be a problem for the novice, but if you really understand it, there is no problem, let's talk about this.
JS, the value of this depends on the calling pattern (the calling object), while JS has 4 invocation modes:
1. Function call mode
When a function is not a property of an object, it is called as a function, and the this in the function points to the global object (the large logarithm is window)
window.value=1;
function GetValue () {
console.log (this.value);
}
GetValue ()//Output 1, this point to window
2. Method invocation Pattern
When a function is a property of an object, we call it a method of the object, and when a method is called, this points to the object
var obj={
Value:2,
getvalue:function () {
console.log (this.value);//output 2,this point to Obj
}
}
!!! In this pattern, this to the object's binding occurs when the method is invoked
3. Constructor call pattern
A function called with new is called a constructor function, and this point points to an object that is an instance of the constructor function
Function Main (val) {
this.value=val;
}
Main.prototype.getvalue=function () {
console.log (this.value);
}
var fun=new main (3);
Fun.getvalue ();
fun.value;//output 3,this The instance object that points to main fun
4.apply/call Call mode and bind
The Apply, call, and bind methods let us set the caller's this point to WHO
function Showvalue () {
console.log (this.value);
}
var obj={
value:4
}
showvalue.call (obj)/output 4,this point to obj object
ECMA5 new Bind method, the specific use can be Google, here is to demonstrate the use of this binding
function Showvalue () {
console.log (this.value);
}
var obj={
value:4
}
var showvalue2=showvalue.bind (obj);
ShowValue2 ()//output 4,this point to obj object
Bind has a lot of uses, you can check it yourself.
The above cliché JS this point is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.