this

139 阅读1分钟

一. 在标准函数中,this引用的是调用函数的上下文对象

  1. 直接调用 ——fn(),this一定是window
  2. 作为对象的方法被调用——obj.fn(),this是调用它的对象obj
  3. 使用apply/call/bind方法调用——fn.apply(null,arguments),this是为它指定的值,为null或undefine时指向window
window.identity = 'The Window';

let object = {
  identity: 'My Object',
  getIdentityFunc() {
    return function() {
      return this.identity;
    };
  }
};

console.log(object.getIdentityFunc()()); // 'The Window'
var obj = {  foo: function(){
    console.log(this)
  }
}

var bar = obj.foo
obj.foo() // 打印出的 this 是 obj
bar() // 打印出的 this 是 window

二. 在箭头函数中,this引用的是定义箭头函数的上下文对象

在严格模式下,调用函数时如果没有指定上下文对象,则this值不会指向window。除非使用apply()call()把函数指定给一个对象,否则this的值会变成undefined

  "use strict"
  var color = "blue"
  function test(){
    console.log(this.color)
  }
  test() // Uncaught TypeError: Cannot read property 'color' of undefined