Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
946 views
in Technique[技术] by (71.8m points)

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??

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...