getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
177.87k stars 33.39k forks source link

The lexical binding of an arrow-function cannot be overridden (even with `new`!) #1841

Closed VovaSv closed 9 months ago

VovaSv commented 9 months ago

https://github.com/getify/You-Dont-Know-JS/blame/59d33b0c47c214270b87e7afd5670ad864d8a465/this%20%26%20object%20prototypes/ch2.md#L797

Please correctly if I'm wrong but in ch2 was said that "The lexical binding of an arrow-function cannot be overridden (even with new!)"

But in an example below the new foo() do override the lexical binding of an arrow-function, isn't true?

function foo() {
    console.log('foo this is :' , this)
    return (a) => {
      debugger;
        // `this` here is lexically adopted from `foo()`
        console.log('from arrow', this.a );
    };
}

var obj1 = {
    a: 2
};

var obj2 = {
    a: 3
};

foo.bind( obj1 );
var bar = new foo(); // new override lexical scope of arrow function
bar(); 
VovaSv commented 9 months ago

Wrong assumption. In example above we actually override by new "new foo()" a this and not a lexical binding of arrow function which is actually a foo functions itself.

getify commented 9 months ago

'new' is called on the foo function, not on the arrow function it returns (assigned to bar).

VovaSv commented 9 months ago

@getify So in simple words "The lexical binding of an arrow-function cannot be overridden (even with new!)" because we basically can't even call arrow function with new (as no constructor in arrow func)?

getify commented 9 months ago

correct