1

I am following the notes on ES6 from this link and created a small code snippets to play around.

class Bar{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
}
let bar = new Bar(12,10);
Bar.prototype.foo =function(){
    return this.x + this.y;
}
bar.foo() // 22 correct

I am so happy until i do this.

let baz = bar.foo
baz(); // NaN

Why baz() is printing NaN ?

John Doe
  • 125
  • 1
  • 11

2 Answers2

3

You took a seperate function from an object and you miss this. To make that work, you need to bind the object to the function.

class Bar{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
}
let bar = new Bar(12,10);
Bar.prototype.foo =function(){
    return this.x + this.y;
}
console.log(bar.foo()) // 22 correct

let baz = bar.foo.bind(bar); // bind innstance

console.log(baz()); // 22
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
2

When you affect bar.foo to baz, the function loses its context (this). So no more this.x and this.y. Check with breakpoints, you will see that both are undefined.

So adding two undefined together produces a NaN.

Try with this too check in your browser :

class Bar{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
}
let bar = new Bar(12,10);
Bar.prototype.foo =function(){
    debugger;
    return this.x + this.y;
}

Try to call it with defining its context. 3 ways to do it :

let baz = bar.foo.bind(bar);
baz();

bar.foo.call(bar);

bar.foo.apply(bar);
MathKimRobin
  • 1,123
  • 2
  • 18
  • 41