Raito
Raito

Reputation: 1573

Can I conserve the default this by using Function.bind ? If no, why?

Let's say I have a function :

function onSomethingChanged(field, evt) {
    this.validate(field, evt.target.value);
}

And I have a React component where I do :

<input onChanged={this.onSomethingChanged.bind(null, "username")} />
  1. Does my this is conserved if I pass null as thisArg ?
  2. If not, how could I conserve it without using explicitly this (without writing this.onSomethingChanged.bind(this, "username")).
  3. If not (again), why JavaScript prevent that? Is there a workaround?

Thanks !

Upvotes: 0

Views: 57

Answers (2)

alexpods
alexpods

Reputation: 48487

No, context (this) of the function will be null in strict mode and global object (window) in non-strict mode

If you don't like bind approach you can use ES6 arrow functions to handle this:

<input onChanged={()=>this.onSomethingChanged("username")} />

or if you don't like parenthesis:

<input onChanged={$=>this.onSomethingChanged("username")} />

where $ is event object (can be replaced by e or any other character at your taste).

Upvotes: 1

user133688
user133688

Reputation: 7064

No. This is the first argument past into any function. By passing in null you're saying the this is null.

Do this instead.

<input onChanged={this.onSomethingChanged.bind(this, "username")} />

Upvotes: 0

Related Questions