2014-04-06 50 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將意味着在不同的上下文別的東西。