Why cannot use lambda to define prototype function

前端 未结 3 534
一个人的身影
一个人的身影 2021-01-11 13:24

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.



        
3条回答
  •  悲&欢浪女
    2021-01-11 14:03

    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);
        }
    }
    

提交回复
热议问题