the way this work with function

In Javascript, this keyword wasn't easy thing for understand. Its can be a tricky thing. Because in javascript context, functions behave differently depending on how you call them.

This is a short article how this keyword work with function:

  • Method Call
  • Function Call
  • Constructor Call
  • Apply Call

Method Call

This pattern is similar like PHP, C++, Java...

This pattern of using function will look the most familiar language (C, Java, PHP, Perl...). That mean: If you define one Object, and when you execute a method, this will be a Object that owns it.

var Object = {
  name : 'Example Object',
  sayHello: function() {
    // this == Object
    return this.name;
  }
}
Object.sayHello(); // return 'Example Object'

Function Call

This patten may look stranger, but when working with javascript, you'll see there is a logic behind it.
When we create a function not associated with an object, in that function this will bound to the global object (usually is window). Because every function in javascript must be bound to an object, and the default to the top level object (window).

var functionCall = function() {
  // this == window
  console && console.log(this);
}
// both result in the same
function functionCall() {
  // this == window
  console && console.log(this);
}
functionCall(); //log the window object to Firebug Console.

Open firebug and see the log


However, this pattern applies anywhere you define function, not just a global level. This is a usually problem user have.

var Change1 = {
  name: 'I was Change1',
  sayHello: function() {
    // this == Change1
    var concat = function(first, second) {
      // this == window (not Change1)
      this.name = first + second;
    };
    concat(this.name, ', but i just change window!');
  }
}
Change1.sayHello(); //set window.name = 'I was Change1, but i just change window!';

Use self to solve this problem:
var Change2 = {
  name: 'I was Change2',
  sayHello: function() {
    // this == Change2
    var self = this;
    var concat = function(first, second) {
      // this == window (not Change2)
      // self == Change2
      self.name = first + second;
    };
    concat(this.name, ', and still am!');
  }
}
Change2.sayHello(); //set Change2.name = 'I was Change2, and still am!';

Categogy: 

Tags: 

Add new comment