【javascript笔记】this in javascript

来源:互联网 发布:网络教研平台 编辑:程序博客网 时间:2024/05/17 22:47

之前一直对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对象
    //chrome F12      window===this  //true    //node     global===this  //true

函数上下文
函数里面的this我理解的是谁调用这个函数,这个this就是指代的调用该函数的对象。

    (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

0 0
原创粉丝点击