箭头函数【JavaScript基础面试题】

箭头函数不能用于构造函数

先看看普通函数是否能当作构造函数用

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

codereasy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值