js函数&箭头函数

2020-06-21  本文已影响0人  pengkiw

1⃣️ 函数前提

//函数预定义 会将函数前提
console.log(sum(3, 4)) //  7
function sum(x, y) {
    return x + y;
}
console.log(sum(3, 4)) //  ReferenceError: Cannot access 'sum' before initialization
let sum = function(x, y) {
    return x + y;
}

2⃣️ 箭头函数
1)this 指向定义时所在的对象,而不是调用时所在的对象

2)不可以当作构造函数

function People(name, age) {
    this.name = name
    this.age = age
}
let p1 = new People('kiw', 18);
console.log(p1)  //People {name: "kiw", age: 18}
let People = (name, age) => {
    this.name = name
    this.age = age
}  
let p1 = new People('kiw', 18); //TypeError: People is not a constructor
console.log(p1)

3)不可以使用arguments对象

let sum = (x, y) => {
   console.log(arguments) // ReferenceError: arguments is not defined
   x + y;
};
上一篇下一篇

猜你喜欢

热点阅读