Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot use lambda to define prototype function

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

this doesn't work

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

and this is fine of course:

Book.prototype.printTitle = function() {
         console.log(this);
         console.log(this.title);
    }
like image 904
stt106 Avatar asked Mar 26 '16 10:03

stt106


People also ask

What does lambda mean in python?

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.

Do all functions have a prototype property?

A Function object's prototype property is used when the function is used as a constructor with the new operator. It will become the new object's prototype. Note: Not all Function objects have the prototype property — see description.

Are arrow functions lambdas?

JavaScript arrow functions are roughly the equivalent of lambda functions in python or blocks in Ruby. These are anonymous functions with their own special syntax that accept a fixed number of arguments, and operate in the context of their enclosing scope - ie the function or other code where they are defined.


2 Answers

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);
    }
}
like image 52
T.J. Crowder Avatar answered Oct 21 '22 01:10

T.J. Crowder


The Arrow function would resolve the context this belongs to the scope where the function was defined. I believe you have defined that function in window scope. So the this will point to window in your function.

You can use normal anonymous function here. And we have to be careful while using arrow functions.

like image 36
Rajaprabhu Aravindasamy Avatar answered Oct 21 '22 00:10

Rajaprabhu Aravindasamy