stt*_*106 11 javascript lambda
有人可以解释为什么用lambda表达式定义原型函数不起作用?我以为必须先问这个但是找不到它.
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);
}
Run Code Online (Sandbox Code Playgroud)
这不起作用
Book.prototype.printTitle2 = () => {
console.log(this.title);
}
Run Code Online (Sandbox Code Playgroud)
这当然很好:
Book.prototype.printTitle = function() {
console.log(this);
console.log(this.title);
}
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 13
其中的箭头功能的主要特点是,他们关闭了在this从其中产生它们的上下文; 他们根据他们像其他功能一样被调用的方式得不到它.所以...
// ...whatever `this` is *here*
Book.prototype.printTitle2 = () => {
// ...is what `this` will be *here*
console.log(this.title);
};
Run Code Online (Sandbox Code Playgroud)
但是你的功能取决于this它的调用方式.
这不是箭头功能的用例.使用正常功能:
Book.prototype.printTitle2 = function() {
console.log(this.title);
};
Run Code Online (Sandbox Code Playgroud)
或者更好的是,使用新class语法:
class Book {
constructor(title, year) {
this.title = title;
this.year = year;
}
printTitle2() {
console.log(this.title);
}
}
Run Code Online (Sandbox Code Playgroud)
该Arrow function会解决的背景下this属于这里定义的功能范围.我相信你已经在window范围内定义了这个功能.所以this意志指向window你的功能.
你可以anonymous function在这里使用普通.使用箭头功能时我们必须小心.
| 归档时间: |
|
| 查看次数: |
1864 次 |
| 最近记录: |