Javascript私有方法问题

时间:2012-02-08 11:00:12

标签: javascript oop

我认为下面的错误非常容易修复,对于那些不是newb的人(像我一样)

任何人都可以告诉我为什么在下面的代码中调用“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();

}

4 个答案:

答案 0 :(得分:1)

不,你把它作为“坏人”的那条线实际上是正确的。 进一步说,您正在尝试执行slideNext函数,然后为结果分配一个函数。它应该是这个;

this.slideNext = function (){
    this.currentFrame ++;
    console.log('  next this.currentFrame  : ' +this.currentFrame );
}   
希望我帮助

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

this根据函数的调用方式为每个函数提供不同的引用/上下文。在您的代码段中,您正在调用start函数()(就像那样调用)将引用其global object中的this context variable,用于非ES5严格和undefined在ES5严格。

要解决该问题,您可以将“外部”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脚本。

答案 3 :(得分:0)

如果您不打算将ScoopANimation用作构造函数,那么我个人就会放弃使用'this':

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();
}
相关问题