【javascript笔记】this in javascript

之前一直对this的理解就是大概知道是个什么东西.最近看到MDN上面的介绍,就记录一下。
mdn官方英文解释:The this keyword refers to the function’s execution context.

全局上下文

  • 全局上下文咱们可以理解为 在 [Object Function] 和 [Object object] 类型 以外的所有 this 对象。
    chrome devTool下 this为全局window对象.
    node 环境下 this为全局global对象

如果this 没有处于函数内部,则是位于全局上下文,全局上下文里面this指代全局对象。

    //chrome F12  
    window===this  //true

    //node 
    global===this  //true

函数上下文
函数里面的this我理解的是谁调用这个函数,这个this就是指代的调用该函数的对象。特殊情况,构造函数里面的this对象以及事件处理函数里面的this,分别代表着返回的new对象,和触发事件的对象。

    (function(){console.log(this==global)})()  //node环境下为true
    (function(){console.log(this==window)})()  //浏览器环境下为true
但是构造函数有点特殊,当一个函数被作为一个构造函数来使用
(使用new关键字),它的this与即将被创建的新对象绑定。

参考资料请点击:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this#构造函数中的_this

posted on 2016-04-28 23:51  狂奔的冬瓜  阅读(194)  评论(0编辑  收藏  举报