[英]Why cannot use lambda to define prototype function
有人可以解釋為什么用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);
}
這不起作用
Book.prototype.printTitle2 = () => {
console.log(this.title);
}
這當然很好:
Book.prototype.printTitle = function() {
console.log(this);
console.log(this.title);
}
其中的箭頭功能的主要特點是,他們收 , 較 this
從他們正在創建的上下文; 他們根據他們像其他功能一樣被調用的方式得不到它。 所以...
// ...whatever `this` is *here*
Book.prototype.printTitle2 = () => {
// ...is what `this` will be *here*
console.log(this.title);
};
但是你的功能依賴於this
變化取決於它的調用方式。
這不是箭頭功能的用例。 使用正常功能:
Book.prototype.printTitle2 = function() {
console.log(this.title);
};
或者更好的是,使用新的class
語法:
class Book {
constructor(title, year) {
this.title = title;
this.year = year;
}
printTitle2() {
console.log(this.title);
}
}
該Arrow function
就解決的背景下this
屬於這里定義的功能范圍。 我相信你已經在window
范圍內定義了該函數。 所以this
將指向你函數中的window
。
你可以在這里使用普通的anonymous function
。 使用箭頭功能時我們必須小心。
除了@ tj-crowder的答案之外 ,我還想留下一個測試用例(mocha assert),你可以使用它來可視化哪些不起作用。
你也可以在這里閱讀更多關於箭頭函數范圍的內容: 你不了解 Kyle Simpson的JS ,他詳細解釋了this
。
基本上,一個箭頭功能的this
指向當前的背景下,它派上用場,如果你已經封閉功能的周邊環境。 它的作用基本上是做var self = this;
事情。
或者凱爾說:
[...]詞匯
this
在前面片斷的箭頭回調函數現在指向相同的值如在包圍makeRequest(..)
的功能。 換句話說,=>
是var self = this
的語法替身。在
var self = this
(或者,函數.bind(this)
調用)通常會有用的情況下,=>
arrow函數是一個更好的替代操作,基於相同的原理。 [...]
你可以用我的要點自己測試一下: https : //gist.github.com/jay-bricksoft/96738dd8a48ceb9f517e914b834cc1ee
在我的測試用例中,這是輸出:
Lambda
function(){}
√ should equal function´s type
1) should have equal context as function
2) should be able to be used as constructor
1 passing (39ms)
2 failing
1) Lambda function(){} should have equal context as function:
AssertionError: 'undefined' == 'string'
+ expected - actual
-undefined
+string
at Context.<anonymous> (test\index.js:29:14)
2) Lambda function(){} should be able to be used as constructor:
TypeError: construct_l is not a constructor
at Context.<anonymous> (test\index.js:34:20)
編輯:添加了示例/參考凱爾辛普森的“你不知道的ES6” https://github.com/getify/You-Dont-Know-JS/tree/master/es6%20%26%20beyond
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.