JavaScript this
函数与 this
1 | function public() { |
从代码的角度看,this
代表的是一个对象,具体代表的是执行调用 public
的当前对象,this 英文中的意思是这个
,这个就是调用public
方法的对象
可以使用’.’运算符、 call,apply,bind
来决定 this
的参考对象
全局对象 与 this
ES6 之前 JavaScript 并没有名称管理机制,如 Number/Math 等都是作为全局对象的特性存在。
1 | // window 下的 Math |
调用函数时,无法通过 ‘.’ 运算符,call/apply 等方式,指定 this,严格模式下,this 为 undefined。非严格模式下,全局作用域下调用 this 代表 window
1 | ; |
函数是 Function 构造函数的实例,如下 demo 可以创建 Function 实例取全局对象
1 | Function('return this')() |
箭头函数与 this
箭头函数可以看成是函数字面量的语法糖。箭头函数在 this 方面的解析与函数字面量不同
1 | this.x = 1 |
字面量函数的 this,由调用者决定。箭头函数的 this 由词法环境决定,即箭头函数在哪个环境中定义的,则 this 代表哪个环境。this 具有继承性。使用
obj.fnArrow.call(obj)
也无法改变 this。箭头函数中 this 一旦绑定,就无法改变。
1 | this.x = 1 |