首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

javascript 中this的了解

2012-08-24 
javascript 中this的理解var test windows testvar foo function(){var test foos testalert

javascript 中this的理解

var test = "window's test";var foo = function(){           var test ="foo's test";           alert(this == window);      // false,这里的this 指向new关键字生成的对象;           alert(this.test);      //  undefined;           return function(){                  var test = "foo's inner test";                  alert(this == window);         // true ,this 指向调用该匿名函数的对象,即window对象;                  alert(this.test);                    // "window's test";           }}var t = new foo();t();        // 等价于 window.t(); var bar = {      test : "bar's test",      method: function(){             alert(this == window);          // false,这里的this 指bar;             return this.test;    //  "bar's test";      }}bar.method();           // false , "bar's test";

总结:

this始终指向调用this所在函数的对象

热点排行