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

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


示例代码
例1:
// 浏览器中
console.log(this);

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

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

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

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

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

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

例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常见的陷阱及避坑建议( ̄. ̄)