一张图学习常见this的指向

1,103 阅读1分钟

在写JS代码时,this的出场频率颇高,担负了传递对象,作用域等等功能,堪称全能超人。

superman
但是this复杂多变,初学的时候想弄清楚并不简单,绕着绕着就迷路了。

“我是谁?我从哪来?我要到哪去?”

road
对于常见的this指向总结成一张简图,佐以示例代码食用,味道更佳。
this

示例代码

例1:

// 浏览器中
console.log(this);

d1

例2:

// Node.js cli中
console.log(this);

d2

// Node.js module中
// 具体原因可查看Node模块作用域知识
//main.js
console.log(this === global);
console.log(this === module.exports); 

d3

例3:

//浏览器中
function foo() {
    console.log(this);
}
foo();

d4
例4:

//浏览器中
function foo() {
    "use strict";
    console.log(this);
}
foo();

d5

例5:

// 浏览器中
var _this;
function Foo() {
    _this = this;
}
var foo = new Foo();
console.log(_this);
foo === _this;

d6

例6:

// 浏览器中
var foo = {
    method: function() {
        console.log(this === foo);
    }
}
foo.method();

d7

例7:

// 浏览器暂不支持ES6语法,在Node 8.0以上版本试验
// test.js
function foo() {
	let bar = () => {
		console.log('from bar->' + this);
	};
	console.log('from foo->' + this)
	bar();
	// 箭头函数免疫call/apply修改作用域
	bar.call(666); 
}
foo.call(555);
foo.call(777);

下一次总结this常见的陷阱及避坑建议( ̄. ̄)

参考

2ality.com/2014/05/thi…