I just learned the front-end not long ago, and I have some questions about the writing method of event monitoring in React.
The writing methods I know are:
Pass the bind function in the constructor
When defining a function, use the shear function definition
hanlde = (e)=> {
}
Use the shear function in the tag
<button onClick={(e)=>this.handleClick(e)}>
</button>
What I don’t understand is the third way of writing
<button onClick={(e)=>this.handleClick(e)}>
</button>
I personally think that arrow function and bind should be different ways of writing the same thing. But I wrote a demo
var name = 'outside'
var obj = {
name: 'inside',
getName1: function() {
return function() {
return this.name;
};
},
getName2: function() {
var func = function(s) {
return function() {
return s;
}
};
return func(this.name);
},
getName3: function () {
var func = ()=> this.name;
return func;
},
getName4: function () {
var func = function() {
return this.name;
};
func = func.bind(this);
return func;
},
getName5 :function () {
var func = function() {
return this.name;
};
var func2 = ()=>func();
return func2;
}
};
console.log(obj.getName1()());//undefine或outside
console.log(obj.getName2()());//inside 通过闭包解决
console.log(obj.getName3()());//inside 通过箭头函数
console.log(obj.getName4()());//inside 通过bind函数
console.log(obj.getName5()());//undefine或outside ???不理解
In getName3, 4, and 5, what getName5 returns is not inside? ?
Maybe the problem lies in my misunderstanding of arrow functions and bind?
Hope to get guidance from seniors
The arrow function in 5 does not bind this when calling func, so this of func points to window
Just change it to this
Or this:
Newly defined functions have their own this value. In non-strict mode in the browser, this this points to the window. If a function is called as an object method, its this points to the object on which it was called. In the example, the
getName5()
中的函数func
, 并非作为obj
object method is called, therefore, its this points to window. Nothing to do with arrow functions.@Xeira is right, when the arrow function is defined, this within the lexical scope is bound to its outer lexical scope, while ordinary functions are specifically bound when they need to be called. It is recommended to read the explanation about this in You-Dont-Know-JS, it is very clear