Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...