2014-04-06 53 views
0

中调用一个方法,我得到test is not defined调用stop()方法尝试将功能

http://jsfiddle.net/n4mKw/1766/

<span id="rotator"></span> 

var rotate = { 
    quoteIndex: -1, 
    duration: 500, 
    delay: 3000, 
    play: true, 
    quotes: [], 
    init: function (quotes) { 
     this.quotes = quotes; 
     this.showNextQuote(); 
    }, 
    showNextQuote: function() { 
     this.quoteIndex = (this.quoteIndex + 1) % this.quotes.length; 
     if (this.play) { 
      $("#rotator").html(this.quotes[this.quoteIndex]) 
       .fadeIn(this.duration) 
       .delay(this.delay) 
      .fadeOut(this.duration, this.showNextQuote.bind(this)); 
     } 
    }, 
    stop: function() { 
     this.play = false; 
    } 



}; 

var test = rotate.init(["example1", "example2", "example3"]); 
test.stop(); 
+3

'rotate.init'不返回任何内容,因此'test'是'undefined' – zerkms

回答

1

您的函数没有返回指定上一个答案的旋转对象的实例。然而,你可以解决这个问题的方法是将对象的实例返回给测试变量。

var rotate = { 
    quoteIndex: -1, 
    duration: 500, 
    delay: 3000, 
    play: true, 
    quotes: [], 
    init: function (quotes) { 
     this.quotes = quotes; 
     this.showNextQuote(); 
     return this; 
    }, 
    showNextQuote: function() { 
     this.quoteIndex = (this.quoteIndex + 1) % this.quotes.length; 
     if (this.play) { 
      $("#rotator").html(this.quotes[this.quoteIndex]) 
       .fadeIn(this.duration) 
       .delay(this.delay) 
      .fadeOut(this.duration, this.showNextQuote.bind(this)); 
     } 
     return this; 
    }, 
    stop: function() { 
     this.play = false; 
     return this; 
    } 



}; 

var test = rotate.init(["example1", "example2", "example3"]); 
test.stop(); 

我已更新代码以返回函数中的对象。请在小提琴中测试它。

1

您可能希望rotate.stop()代替时。 test不是rotate的一个实例,因为init不返回对象或任何对此事。

1

每个JavaScript函数都会返回一些东西,如果你不指定返回值,它将默认返回undefined。你现在正在做的是分配那个未定义的值来测试和调用stop(),这是无效的。如果你试图链接对象,只需从init函数返回。

var rotate = { 
    quoteIndex: -1, 
    duration: 500, 
    delay: 3000, 
    play: true, 
    quotes: [], 
    init:function() 
    { 
    this.quotes = quotes; 
    this.showNextQuote(); 
    return this; 
    }, 
    showNextQuote: function() { 
    //showNextQuote stuff..... 
    }, 
    stop:function(){ 
    this.play = false; 
    } 

}

小心你如何使用“this”关键字though..it将意味着在不同的上下文别的东西。