为什么不能使用lambda来定义原型函数 [英] Why cannot use lambda to define prototype function
问题描述
有人可以解释为什么用lambda表达式定义原型函数不起作用?我以为必须先问这个但是找不到它。
Can someone please explain why defining a prototype function with lambda expression doesn't work? I thought this must be asked before but couldn't find it.
function Book(title, year) {
this.title = title;
this.year = year;
// define a function within the object, which works fine
this.printYear = () => console.log("instance function of an object: " + this.year);
}
这不起作用
Book.prototype.printTitle2 = () => {
console.log(this.title);
}
当然没问题:
Book.prototype.printTitle = function() {
console.log(this);
console.log(this.title);
}
推荐答案
其中一个主要特征箭头函数是它们从它们创建的上下文中关闭 这个;他们根据他们像其他功能一样被调用的方式得不到它。所以......
One of the chief features of arrow functions is that they close over the this
from the context in which they're created; they don't get it based on how they're called like other functions do. So...
// ...whatever `this` is *here*
Book.prototype.printTitle2 = () => {
// ...is what `this` will be *here*
console.log(this.title);
};
但是你的函数依赖于这个
会有所不同关于如何调用它。
But your function relies on this
varying depending on how it's called.
这不是箭头函数的用例。使用普通函数:
This just isn't a use-case for arrow functions. Use a normal function:
Book.prototype.printTitle2 = function() {
console.log(this.title);
};
或者更好的是,使用新的类
语法:
Or better yet, use the new class
syntax:
class Book {
constructor(title, year) {
this.title = title;
this.year = year;
}
printTitle2() {
console.log(this.title);
}
}
这篇关于为什么不能使用lambda来定义原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!