THIS使用场景总结

1.给当前元素的某个事件绑定方法,当事件触发方法执行的时候,方法中的this是当前操作的元素对象

oBox.onclick = function(){
	// => this为oBox
}

2.普通函数执行,函数中的this取决于执行的主体,谁执行的this就是谁
由于立即执行函数无对象调用,this为window(严格模式下,没有点this是undefined)

let fn = function () {
	console.log(this.name);
};
let obj = {
	name: '哈哈',
	fn: fn
};
fn(); //this:window
obj.fn();//this:obj

3.构造方法执行,方法体中的this是当前类的一个实例

let Fn = function() {
	this.x = 100; //this:f
};
let f = new Fn;

4.箭头函数中没有自己的this,this是上下文中的this

let obj = {
	fn: function() {
		//this:obj
		setTimeout(() => {
			//this: obj
		}, 1000)
	}
}
obj.fn()

5.在小括号表达式中,会影响this的指向

let obj = {
	fn: function(){
		console.log(this);
	}
}
obj.fn();//this:obj
(12, obj.fn)();//this:window

6.使用call/apply/bind可以改变this指向

fn.call(obj);//this:obj
fn.call(12)//this:12
fn.call();//=>this:window,非严格模式下call/apply/bind第一个参数写null或undefined或不写,this都是window,
//严格模式不写是undefined
var n = 2;
var obj = {
  n: 3,
  fn: (function (n) {
    n *= 2;
    this.n += 2;
    var n = 5;
    return function (m) {
      this.n *= 2;
      console.log(m + (++n))
    }
  })(n)
};
var fn = obj.fn;
fn(3);
obj.fn(3);
console.log(n, obj.n);//9, 10, 8, 6

猜你喜欢

转载自blog.csdn.net/weixin_42098339/article/details/89609232