2015-11-13 34 views
0

我正在探索开源开发和使用yeoman和淘汰赛发电机与十字路口和requirejs。我已经看过ES6类和构造函数,并且我并不完全理解在某些情况下,在可见性不是ES6类或函数模式中发生的函数错误的情况下,敲除操作会发生什么。所以我以前在淘汰赛中已经看到过这种行为,但是如果可以的话,我想要一些额外的细节。淘汰赛观察不是一个函数错误

一个codepen这里的这种行为:http://codepen.io/srabeeh/pen/pjqweX?editors=001

有人能解释失败的功能查找的来源是什么? 代码:

class Circle { 
    constructor(diameter, quality) { 
     this.diameter = ko.observable(diameter); 
     this.quality = ko.observable(quality); 
    } 

    updateCircle(){ 
    console.log('updating...'); 
    // the correct way to update an observable 
    // this line fails with diameter is not a function - uncomment to see error 

    // this.diameter(this.diameter() +1); 

    // this works but i fear this obliterates the observable 
    this.diameter += 1; 

    console.log(this.diameter); // gives NaN of course as it's an observable 

    //function call fails that it's not a function 
    console.log(this.diameter()); 

    } 

    startTimer(){ 
     var timer = setInterval(this.updateCircle, 1000) 
    } 
}; 

let c = new Circle(270, 5); 
c.startTimer(); 

感谢

+0

你检查过这个指针是否在updateCircle方法中正确吗?否则你可能需要绑定它。 – Tarion

+0

偏离主题,但这是什么样的你和你不明白和不需要的东西?摆脱所有的烦恼,并从基础开始。不要惹你不明白的东西。如果你不理解它,你不需要它。除非你明白它是什么,并认识到你的需要,否则不要使用某些东西。不要一下子试试一切。分解它,并一次采取一件事。在进入ES6,requirejs和yoeman之前,了解自己的淘汰赛,以及这个十字路口的东西是什么?我从来没有听说过它。 – hasen

回答

0

它实际上是与这个指针的问题。试试这个:

class Circle { 
    constructor(diameter, quality) { 
    this.diameter = ko.observable(diameter); 
    this.quality = ko.observable(quality); 
    } 

    updateCircle() { 
    console.log('updating...'); 
    this.diameter(this.diameter() + 1); 
    console.log(this.diameter()); 

    } 

    startTimer() { 
    var timer = setInterval(function() { 
     this.updateCircle() 
    }.bind(this), 1000) 
    } 
}; 

let c = new Circle(270, 5); 
c.startTimer(); 
console.log("started") 

注意绑定。

+0

我记得这个问题。再读一遍“this”和“bind”。好奇,有没有办法给updateCircle()方法正确的上下文或绑定“this”而不更改计时器?例如“var self = this;”?这是一个好的模式还是bind()是更审慎的方法? –

+0

是的。因为lambda语法总是保留这种状态,所以找出如何查看typecript编译setInterval(()=> {this.doStuff()}),1000)的方法。 - 当然还有许多关于“这个”问题的其他资源。我个人喜欢坚持像所有我的js代码打字稿一样的transpile。 – Tarion