为什么不能使用lambda来定义原型函数

时间:2016-03-26 10:43:25

标签: 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);
}

这不起作用

Book.prototype.printTitle2 = () => {
        console.log(this.title);
    }

当然没关系:

Book.prototype.printTitle = function() {
         console.log(this);
         console.log(this.title);
    }

3 个答案:

答案 0 :(得分:13)

箭头函数的一个主要特征是它们从它们创建的上下文中关闭 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);
    }
}

答案 1 :(得分:8)

Arrow function将解析上下文this属于定义函数的范围。我相信你已在window范围内定义了该功能。因此,this会在您的函数中指向window

您可以在此处使用普通anonymous function。使用箭头功能时我们必须小心。

答案 2 :(得分:0)

除了@t-j-crowderanswer之外,我还想留下一个测试用例(mocha断言),您可以使用它来可视化哪些无效。

此外,您可以在此处详细了解箭头功能的范围: You Don't Know JS 作者:凯尔辛普森,他详细解释了this

基本上,箭头函数this指向当前上下文的周围上下文,如果你有封闭函数,它会派上用场。 它的作用基本上是做var self = this;事。

或者凯尔说:

  

[...]   上一个代码段中箭头函数回调中的词法this现在指向与封闭makeRequest(..)函数中的值相同的值。换句话说,=>var self = this的语法替代。

     

如果var self = this(或者,函数.bind(this)调用)通常会有所帮助,=>箭头函数是以相同原则运行的更好的替代方法。 [...]

你可以用我的要点自己测试一下: 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)

编辑:添加了Kyle Simpson的“你不知道的ES6”的例子/参考 https://github.com/getify/You-Dont-Know-JS/tree/master/es6%20%26%20beyond