javaScript-this

100 阅读1分钟

this指向规律

1、在函数中,非显式或隐式的简单调用时,在严格模式下,函数内的this会被绑定到undefined上,在非严格模式下则会被绑定到全局对象window/global上

2、一般使用new方法调用构造函数时,构造函数内的this会被绑定到新创建的对象上

3、一般通过call/apply/bind方法显式地用用函数时,函数体内的this会被绑定到指定参数的对象上

4、一般通过上下文对象调用函数时,函数体内的this会被病毒到该对象上。

5、在箭头函数中,this的指向是由外层(函数或全局)作用域来决定的。

示例1:全局变量中的this

function f1() {
  console.log(this)
}
function f2() {
    'use strict'
  console.log(this)
}
f1()
f2()

函数在浏览器全局环境中被简单调用,

  • 在非严格模式下this指向window
  • 通过use strict指明严格模式的情况下this指向 undefined
var person = {
  age: 10,
  fn : function() {
    console.log('fn', this);
    console.log('fn', this.age);
  }
};
var fn1 = person.fn;
fn1()

this仍然指向window,因为person.fn赋值给了全局变量fn1

var person = {
  age: 10,
  fn : function() {
    console.log('fn', this);
    console.log('fn', this.age);
  }
};
person.fn();`

1643548536(1).png

这时,this指向最后调用它的对象 在执行函数时不考虑显示绑定,如果函数中this是被上一级的对象所调用的,那么this指向的就是上一级的对象,否则指向全局环境。

例二:上下文对象调用中的this

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id     : 678,
  fn : function() {
    return this
  }
};
console.log(person.fn() === person)

1643549052(1).png

const person = {
  name: "Bill",
  brother: {
  	name: "Mike",
    fn: function() {
    	return this.name
    }
  }
};
console.log(person.brother.fn())

1643549564(1).png

const o1 = {
  text: "o1",
  fn: function() {
    return this.text;
  }
};
const o2 = {
  text: "o2",
  fn: function() {
    return o1.fn();
  }
};
const o3 = {
  text: "o3",
  fn: function() {
  	var fn = o1.fn;
    return fn();
  }
};
console.log(o1.fn())
console.log(o2.fn())
console.log(o3.fn())

1643549854(1).png