我有两个 JS 函数做同样的事情:
1)
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: function() {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
2)
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: () => {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
请注意,这两段代码之间的唯一区别在于age() 函数的描述方式。据我了解,前者使用的是函数语句,后者使用的是函数表达式。
但是问题是,只有前一段代码返回预期的数据,而后者返回以下错误:
Uncaught TypeError: Cannot read property 'getFullYear' of undefined
at Object.age
我试图理解为什么当两者语法正确时一个有效而另一个无效?
我刚刚开始深入学习 JS,所以详细而直接的答案将不胜感激。谢谢。
最佳答案
据我了解,前者使用函数语句,后者使用函数表达式
不,两者都是函数表达式。唯一的区别是第一个是普通函数,第二个是 ES6 箭头函数。根据 MDN
An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the
this
箭头函数没有自己的 this
绑定(bind)到 this,它将使用绑定(bind)到父作用域的 this
。在上面的例子中,父作用域是全局作用域。因此 this
将引用 window
对象而不是对象。
const obj = {
method:() => console.log(this === window)
}
obj.method()
关于javascript - 为什么这种 JS 函数风格无法检索所需的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227914/