JavaScript 普通函数和箭头函数
·
JavaScript 普通函数和箭头函数
this
- 箭头函数:没有自己的this,因此this指向定义时的上下文,也就是外层。
- function函数:this指向调用时的上下文,也就是调用者。
const user = {
name: "小明",
age: 18,
sayHello: () => {
console.log(`hello: 我是${this.name}`);
}
};
user.sayHello();
// hello: 我是
说明:箭头函数 sayHello 中的 this 指向 user 的上下文也就是全局作用域,全局作用域没有 name 属性,因此没有值输出。
const timer = {
time: 0,
start() {
setInterval(() => {
this.time++;
console.log(this.time);
}, 1000);
}
};
timer.start();
说明:setInterval 中的箭头函数的 this 指向外层的上下文,也就是 start,而 start 的上下文是 timer,因此 this 指向 timer。
const user = {
name: "小明",
age: 18,
sayHello: function () {
console.log(`hello: 我是${this.name}`);
}
};
user.sayHello();
// hello: 我是小明
说明:普通函数 sayHello 中的 this 指向调用者也就是 user,因此输出“小明”。
构造函数
- 箭头函数:没有构造函数。
- function函数:支持构造函数。
const User = (name, age) => {
this.name = name;
this.age = age;
};
const user = new User("小明", 18);
// Uncaught TypeError: User is not a constructor
说明:箭头函数不支持构造函数,因此不能使用 new 的语法。
function User(name, age) {
this.name = name;
this.age = age;
}
const user = new User("小明", 18);
console.log(`姓名:${user.name} 年龄:${user.name}`);
// 姓名:小明 年龄:小明
// 或者使用ES6的class语法
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const user = new User("小明", 18);
arguments
- 箭头函数:没有arguments对象。
- function函数:有arguments对象,arguments是一个类数组对象。
const sayHello = () => {
console.log(arguments);
};
sayHello("hello", "world");
// Uncaught ReferenceError: arguments is not defined
const sayHello = (...args) => {
console.log(args);
};
sayHello("hello", "world");
// ['hello', 'world']
说明:箭头函数不支持 arguments 对象,但是可以通过剩余参数获取。
function sayHello() {
console.log(arguments);
};
sayHello("hello", "world");
// Arguments(2)['hello', 'world', callee: ƒ, Symbol(Symbol.iterator): ƒ]
更多推荐



所有评论(0)