箭头函数不能用于构造函数
先看看普通函数是否能当作构造函数用
var Student=function(age){
this.age=age;
}
var obj=new Student(20);
console.log(obj.age);//20
如果将构造函数改为箭头函数,看看会输出什么结果?发现报错(//Box is not a constructor)
var Box=age=>{
this.myAge=age;
}
var obj=new Box(20);//Box is not a constructor
console.log(obj.myAge);
箭头函数没有 prototype 属性
var Foo = () => {};
console.log(Foo.prototype); // undefined
箭头函数没有arguments
先看看普通函数的 arguments 。可以发现,在普通函数中, arguments 是一个数组,该数组内存放的是调用函数时,外界传进来的参数。
var f = function(i){
return arguments[0]+i;
};
console.log(f(2))//输出4
如果在箭头函数中使用arguments会发生什么?由此可以得出结论,箭头函数内没有 arguments 参数。
var f = (i) => arguments[0]+i;
console.log(f(2))
箭头函数内不能绑定this
箭头函数的 this
完全取决于外层作用域。
示例 1 :
我们发现,下述代码中,greet()
中打印的this,和 outer()
中打印的 this 是一样的。这说明箭头函数的 this 和外层作用域中的 this 是一样的。
function outer() {
console.log(this); // 输出:{ name: 'Alice', greet: [Function: greet] }
const greet = () => {
console.log(this); // 输出:{ name: 'Alice', greet: [Function: greet] }
};
greet();
}
const person = {
name: "Alice",
greet: outer,
};
person.greet();
示例 2 :
箭头函数的 this 在定义的时候决定,而非调用的时候决定。
从下面代码可以看出,arrow() 在 outer() 内部被调用,但是 arrow 的 this 指向的是 window,和 outer 的 this 不同。这说明,在定义 arrow 的时候,它的 this 就已经固定了,是 window。因此,不管在哪里调用 arrow 函数,它内部的 this 始终指向的是 window。
const arrow = ()=>{
//this是什么? window
console.log("this是什么",this);
}
function outer() {
//我是外层函数 {name: 'coderEasy', outer: ƒ}
console.log("我是外层函数",this);
arrow();
}
obj = {
name:"coderEasy",
outer : outer,
}
obj.outer();
无法通过 call()、apply()改变箭头函数的调用者
通过以下例子可以发现,即使用 apply 显示绑定了sayColor() 的调用者,但在实际执行的时候,this 仍指向 red。这说明 apply 绑定失效了。
window.color = "red";
let color = "green";
let obj = {
color: "blue"
};
let sayColor = () => {
return this.color;
};
sayColor.apply(obj);//red