简体   繁体   English

返回NAN的Javascript原型函数

[英]Javascript prototype function returning NAN

I am following the notes on ES6 from this link and created a small code snippets to play around. 我正在通过此链接关注ES6上的注释,并创建了一个小的代码片段供您试用。

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 ? 为什么baz()打印NaN

You took a seperate function from an object and you miss this . 您从一个对象获得了一个单独的函数,而您错过了this To make that work, you need to bind the object to the function. 为了使它起作用,您需要bind对象bind到函数。

 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 

When you affect bar.foo to baz, the function loses its context (this). 当您将bar.foo影响到baz时,该函数将失去其上下文(此)。 So no more this.x and this.y. 因此,不再需要this.x和this.y。 Check with breakpoints, you will see that both are undefined. 检查断点,您将看到两者均未定义。

So adding two undefined together produces a NaN. 因此,将两个未定义的内容相加会产生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 : 3种方法:

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

bar.foo.call(bar);

bar.foo.apply(bar);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM