Javascript私有方法问题

Javascript Private Method Issue

本文关键字:问题 有方法 Javascript      更新时间:2023-09-26

我想,对于不是新手的人来说,下面的错误很容易修复

有人能告诉我为什么下面代码中对"this.slideext()"的调用不起作用吗。显然"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();
}

不,您标记为"坏的一行"的那一行实际上是正确的。更进一步,您正在尝试执行slideNext函数,然后为结果分配一个函数。应该是这样;

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

希望我能帮助

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

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

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

为了解决这个问题,您可以将"外部"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脚本。

如果你不打算将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();
}