Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - Why we need to bind function in React Native?

I am working on a React Native project. On some tutorials I have seen to bind a method like this:

constructor(props){
super(props);
this.my_function = this.my_function.bind(this);
}

My question is if I can access the function in constructor using this.my_function then why I need to bind this again? I have Java and Python background, may be that's why I am confused with this type of method binding. Note: I know that if I don't bind a method in React Native/React JS my method won't work correctly. I just want to know why I need this extra binding.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a look at this link to understand how JS closure works

http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

You need to bind the function so it has access to state and other variables in your class, not just parameters that pass when you execute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...