In js, this pointing must be a difficult problem for novices, but if you really understand it, there will be no problem. Let’s talk about this below.
In JS, the value of this depends on the pattern of the call (the call object), and there are 4 types of calling patterns in JS:
1. Function call mode
When a function is not an object's property, it is called as two functions. At this time, this in the function points to the global object (window in large logarithm)
window.value=1;function getValue(){ console.log(this.value);}getValue();//Output 1, this point to window2. Method calling mode
When a function is an object's property, we call it a method of the object. When a method is called, this points to the object
var Obj={ value:2, getValue:function(){ console.log(this.value);//Output 2, this points to Obj } }! ! ! In this mode, the binding of this to the object occurs when the method is called
3. Constructor call mode
The function called with new is called the constructor function. At this time, this points to the object that comes from the constructor function instance
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 pointes to the instance object fun4. apply/call call mode and bind
The apply, call, bind methods allow us to set who this in the caller points to
function showValue(){ console.log(this.value);}var obj={ value:4}showValue.call(obj)//Output 4, this points to the obj objectA new bind method has been added in ECMA5. You can google the specific usage. Here is a demonstration of the usage of this binding.
function showValue(){ console.log(this.value);}var obj={ value:4}var showValue2=showValue.bind(obj);showValue2()//Output 4, this points to the obj objectThere are many uses of bind, you can check it out by yourself
The above cliché talk about this in js is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.