this operator in javascript

Suppose I have JavaScript code like

      myClass = function(){
          function doSomething(){
              alert(this); // this1 
          }
      } 
      alert(this); //this2

What those two 'this' objects are refer for??

Answers:

Answer

The this value in the global execution context, refers to the global object, e.g.:

this === window; // true

For Function Code, it really depends on how do you invoke the function, for example, the this value is implicitly set when:

Calling a function with no base object reference:

myFunc();

The this value will also refer to the global object.

Calling a function bound as a property of an object:

obj.method();

The this value will refer to obj.

Using the new operator:

new MyFunc();

The this value will refer to a newly created object that inherits from MyFunc.prototype.

Also, you can set explicitly that value when you invoke a function, using either the call or apply methods, for example:

function test(arg) {
  alert(this + arg);
}
test.call("Hello", " world!"); // will alert "Hello World!"

The difference between call and apply is that with apply, you can pass correctly any number of arguments, using an Array or an arguments object, e.g.:

function sum() {
  var result = 0;
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

var args = [1,2,3,4];
sum.apply(null, args); // 10

// equivalent to call
sum(1,2,3,4); // 10

If the first argument value of call or apply is null or undefined, the this value will refer to the global object.

(note that this will change in the future, with ECMAScript 5, where call and apply pass the thisArg value without modification)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.