[JavaScript] this

The “this” object is pretty familiar to the C# developers. It refers to the current object. The “this” keyword is also used in JavaScript, but you need to be careful to use it properly.

What does ‘this’ refers to?

You can use the “this” keyword in any function, and it refers to the owner (context) of the function.

function dummy() {
  alert(this); // [object Window]
};

dummy();

In any global function, “this” refers to the global object, which is the “window” object in browsers.


‘this’ in Objects

If you define a method in an object, “this” refers to the object itself. “this” can access the object’s other properties and members too.

var adder = {
  x: 1,
  y: 2,
  add: function () {
    alert(this); // [object Object]
    return this.x + this.y;
  }
};
 
alert(adder.add()); // 3

Changing the Context – bind()

  • function.bind (thisArg)

For a given function, “bind()” creates a new function that has the same function body but a different owner or context.

var adder = {
  x: 1,
  y: 2,
  add: function () {
    return this.x + this.y;
  }
};
 
var myNum = {
  x: 2,
  y: 3
};
 
alert(adder.add()); // 3
 
// bind the method to a different object
var newAdder = adder.add.bind(myNum);
alert(newAdder()); // 5
 
alert(adder.add()); // still 3

This technique is pretty unique and interesting but can be easily confusing. So use it with care!

(Example) Context Binding with “this” Object in a Class

Context Binding is extremely important when you work with React. When you create a controlled form element, the event handler should be bound to the correct “this” object.

class SearchBar extends React.Component {
  constructor(props) {
    super(props);

    this.state = { term: '' };
    this.onInputChange = this.onInputChange.bind(this);
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onInputChange(event) {
    //console.log(event.target.value);
    this.setState({ 
      term: event.target.value 
    })
  }

  onFormSubmit(event) {
    // do something
    event.preventDefault();
  }

  render() {
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
          <div>
            <label>{this.props.title}</label>
            <input type="text" 
              value={this.state.term}
              onChange={(this.onInputChange)} />
          </div>
        </form>
      </div>
    );
  }
}

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s