最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

this operator in javascript - Stack Overflow

programmeradmin3浏览0评论

Suppose I have JavaScript code like

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

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

Suppose I have JavaScript code like

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

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

Share Improve this question edited Jul 23, 2010 at 17:18 Teja Kantamneni 17.5k12 gold badges57 silver badges86 bronze badges asked Jul 23, 2010 at 17:16 MuhitMuhit 7871 gold badge7 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15

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)

发布评论

评论列表(0)

  1. 暂无评论