this operator in javascript -


suppose have javascript code

      myclass = function(){           function dosomething(){               alert(this); // this1            }       }        alert(this); //this2 

what 2 'this' objects refer for??

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

this === window; // true 

for function code, depends on how invoke function, example, this value implicitly set when:

calling function no base object reference:

myfunc(); 

the this value refer global object.

calling function bound property of object:

obj.method(); 

the this value refer obj.

using new operator:

new myfunc(); 

the this value refer newly created object inherits myfunc.prototype.

also, can set explicitly value when invoke function, using either call or apply methods, example:

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

the difference between call , apply apply, can pass correctly number of arguments, using array or arguments object, e.g.:

function sum() {   var result = 0;   (var = 0; < arguments.length; i++) {     result += arguments[i];   }   return result; }  var args = [1,2,3,4]; sum.apply(null, args); // 10  // equivalent call sum(1,2,3,4); // 10 

if first argument value of call or apply null or undefined, this value refer global object.

(note change in future, ecmascript 5, call , apply pass thisarg value without modification)


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -