设为首页 加入收藏

TOP

匿名函数、构造函数中的this
2017-10-10 16:33:01 】 浏览:4645
Tags:匿名 函数 构造 this

直接上测试代码:


//直接调用

function outer(){

console.log(this);  //this ==> window

(function inner(){

console.log(this); //this ==> window

})();

};

outer();  //函数返回undefined

//通过构造函数调用

function outer(){

console.log(this);  //this ==> outer

(function inner(){

console.log(this); //this ==> window

})();

};

new outer(); //构造函数返回outer

//在obj对象下直接调用

function outer(){

console.log(this);  //this ==> obj对象

(function inner(){

console.log(this); //this ==> window

})();

};

var obj = {};

obj.o = outer;

obj.o();  //函数返回undefined

//在obj对象下通过构造函数调用

function outer(){

console.log(this);  //this ==> outer

(function inner(){

console.log(this); //this ==> window

})();

};

var obj = {};

obj.o = outer;

new obj.o(); //构造函数返回outer

小结:

  1.  this始终指向一个对象,基于函数的执行环境绑定的
  2.  全局环境中,this等于window
  3. 当函数被作为某个对象的方法调用时,this等于那个对象
  4.  构造函数会生成一个新的对象,其内部的this指向这个对象
  5.  匿名函数的执行环境具有全局性,因此其this对象通常指向window。每个函数在被调用时,其活动对象都会自动取得两个特殊变量:this和arguments。内部函数在搜索这两个变量时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量。不过,把外部作用域中的this对象保存在一个闭包能够访问到的变量里。就可以让闭包访问该对象了。
  6. 最后,感谢这个链接的答主,让我加深了对this的理解:https://segmentfault.com/q/1010000004648772
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇微擎app端上传图片后删除不了图片 下一篇HTML <frameset> 标签

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目