2012-02-08 57 views
0

我想,下面的错误是很容易解决的人谁不是一个福利局(像我)的Javascript的私有方法问题

谁能告诉我为什么呼吁“this.slideNext()”中的下面的代码不起作用。显然“this.slideNext()”不是一个函数?

function ScoopAnimation(_path, _start, _end, _delay) { 

    this.start = _start 
    this.end = _end; 
    this.delay = _delay; 
    this.path = _path 
    this.currentFrame = _start; 

    this.slideNext() = function() { 
     this.currentFrame++; 
     console.log(' next this.currentFrame : ' + this.currentFrame); 
    } 

    this.start = function() { 
     console.log('next this.start() : ' + this.currentFrame); 
     //THE NEXT LINE CAUSES THE ERROR! 
     this.slideNext() 
    } 

    this.start(); 

} 
+0

看起来你有你的分号失踪。如果在添加分号时错误仍然存​​在,您可以尝试吗?此外,你可以发布错误消息吗?例如,您可以从Firefox的Web控制台中查看它。 – belgther 2012-02-08 11:03:35

+0

Gotcha。分号不是问题。错误消息是“this.slideNext不是函数”。 Japrescott的解决方案消除了错误。它看起来像我有一个额外的paraenthesis;) – Victor 2012-02-09 09:18:33

回答

1

不,那一行你抨击为“坏的”其实是正确的。 更进一步,您正试图执行slideNext函数,然后将函数分配给结果。它应该是这个;

this.slideNext = function(){ 
    this.currentFrame ++; 
    console.log(' next this.currentFrame : ' +this.currentFrame); 
} 

希望我帮助

+0

你没有错:P – 2012-02-08 11:06:01

+0

你不够快的“赏金猎人”,但因为你在积分,在这里你去! – 2012-02-08 11:27:34

+0

不,我不在意分数,但如果我的回答是正确的,我花时间写它,想要一些承认似乎对我合法:) (因为你不关心点,为什么不捐赠给我?:P) – japrescott 2012-02-08 12:46:41

0

我可能是错的,但不应该是被定义为:

// defined without brackets 
this.slideNext = function(){ 
    this.currentFrame ++; 
    console.log(' next this.currentFrame : ' +this.currentFrame); 
    } 
0

this对每个功能不同的参考/背景的基础上,如何函数被调用。在你的代码片段中,你调用start函数(),其中(就像那样)将在其严格的ES5严格中针对non-ES5 strict和undefined的的this context variable

为了解决这个问题,你可以存储你的“外” this在一个局部变量的引用,就像

var myScope = this; 

,然后你需要访问的任何其他职能范围内使用myScope代替this外部范围。

myScope.slideNext(); 

另一种选择是使用ES5 Function.prototype.bind为函数绑定上下文。这看起来像:

this.start = function() { 
    console.log('next this.start() : ' + this.currentFrame); 
    //THE NEXT LINE CAUSES THE ERROR! 
    this.slideNext() 
}.bind(this); 

现在,我们必然的this当前值的start功能的情况下。现在您可以继续在该功能中使用this。请注意,这只适用于支持ES5的js引擎,或者您已加载某种ES5 Shim脚本。

+0

感谢您的评论。它帮助我更好地理解Javascript中的“this” – Victor 2012-02-11 13:10:27

0

如果您不打算ScoopANimation被用作一个构造函数,那么我会亲自沟使用“这个”:

function ScoopAnimation(_path, _start, _end, _delay) { 

    var start = _start, 
     end = _end, 
     delay = _delay, 
     path = _path, 
     currentFrame = _start; 

    function slideNext() { 
     currentFrame++; 
     console.log(' next this.currentFrame : ' + currentFrame); 
    } 

    function start() { 
     console.log('next this.start() : ' + currentFrame); 
     //THE NEXT LINE CAUSES THE ERROR! 
     slideNext() 
    } 

    start(); 
}