JS 基础系列 之 简单记忆 this 指向

this 的指向案例 烦多,记住游戏规则,方能以 “不变” 应 “万变”。

脑图甜点:

普通函数

直接调用函数:

全局环境 严格模式 this = undefined,非严格模式 this = window

function fn1() {     
    'use strict'    
    console.log(this)
}
function fn2() {     
    console.log(this)
}
fn1(); // Window
fn2(); // undefined
复制代码

构造函数:

this = 构造函数实例

function fn1() {      
    this.name = "fn1";    
    console.log(this);
}
var fn2 = new fn1();
console.log(fn2.name) // fn1
复制代码

方法调用,即 对象.方法:

this = 调用函数的对象

var o1 = {
	name: 'o1',
	fn: function () {  
		return this.name;
	}
}

var o2 = {
	name: 'o2',
	fn: o1.fn
}

console.log(o2.fn()) // o2
复制代码

apply、call、bind

apply、call 传参数不同,bind 需要执行

var obj = {};fn.call(obj, 'arg1', 'arg2');

var obj = {};fn.apply(obj, ['arg1', 'arg2']);

var obj = {};fn.bind(obj, 'arg1', 'arg2')();
复制代码

箭头函数

this = 包裹箭头函数的那个函数的this(就近原则),找不到this,结果 与 全局模式相同

var obj = {
	name: 'obj',
	fn: function () {  
		this.name = 'fn'
		let func = () => {
			console.log(this.name)
		}

		func();
	}
}


obj.fn(); // fn
复制代码

Dom 绑定事件

onclick和addEventerListener中 this 默认指向绑定事件的元素,IE浏览器 指向 attachEvent, 其他 window

小提示:事件中可以使用 箭头函数,尽量避免 this 被改变

优先级

箭头函数 > new > apply,call,bind > 对象.方法 > 直接调用(全局环境)

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享