this-4
ES6函数里的this指的是定义这个函数时外层代码的this,可以理解为:
1、ES6箭头函数没有自己的this;
2、ES6箭头函数的this是外层代码(定义时,非执行时,也就是词法作用域)this的引用。
<script>
var Animal = function () {
this.name = "Animal";
this.speak = (words) => {
console.log(this.name + " is saying " + words + ".");
}
this.diff = function (words) {
console.log(this.name + " is saying " + words + ".");
}
};
var cat = new Animal();
cat.speak("miao!"); // Animal is saying miao!.
cat.diff("common"); // Animal is saying common.
console.log("------------------------");
var speak = cat.speak;
speak("miao!"); // Animal is saying miao!.
var diff = cat.diff;
diff("common"); // is saying common.
</script>
《你不知道的JS》上卷this全面解析章节提到:
<script>
function foo() {
console.log(this.a); // 43
}
var a = 2; //声明在全局作用域中的变量(比如 var a = 2) 就是全局对象的一个同名属性
window.a = 43; // 没有这句的话会打印出2
foo();
</script>

浙公网安备 33010602011771号