2011-08-04 44 views
0

我是一個PHP的傢伙,現在在我的第一插件IM學習

繼承人什麼IM高達

$.plugin.method({ 
    test: 'helloworld' 
}); 

$.plugin.method({ 
    test: 'another helloworld' 
}) 

我的繼承人函數或類?

// class ? 
jquery.plugin = function(){ 
    // variables 
    var test = []; 

    // function ? 
    var method = function(params){ 
     test[] = params['test'] 
    } 
    console.log(test) 
} 

什麼IM期待

test = ['helloworld','another helloworld'] 

我們能做到這一點在JavaScript?我是否正確?

謝謝!

+0

你試過了嗎? – JJJ

+0

是的,我做了,它是空的。讓我再嘗試一次。對不起,方法錯了啊。更新了問題。抱歉。 –

+0

felix,所以$ .plugin.method()是一個函數嗎?不調用插件內的方法? –

回答

3

在你的榜樣,你做一個plugin功能,但在第一個片段您呼叫$.plugin.method()而不是$.plugin()

你不得不做出plugin對象method屬性:

(function($) { 

    // variables 
    var test = []; 

    $.plugin = { 
     method: function(params){ 
      test.push(params['test']); 
      console.log(test) 
     } 
    } 

}(jQuery)); 

的直接功能確保test僅僅是$.plugin本身可見。你無法從外部訪問它。如果你想做到這一點,你必須使它的$.plugin屬性:

$.plugin = { 
    test: [], 
    method: function(params){ 
     this.test.push(params['test']); 
     console.log(test) 
    } 
} 

我建議你先讀一JavaScript guide [MDN guide]瞭解functions [MDN guide]objects [MDN guide]的基礎知識。

+0

很棒的鏈接!!!!。謝謝你felix –

+0

@亞當:不客氣:) –

1

什麼是$ .plugin?我不知道你想要什麼,所以在這裏不用什麼:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
<script type="text/javascript"> 
$.plugin = { 
    // Variable 
    test: [], 

    // Function 
    method: function(params) { 
     this.test.push(params['test']); 
    } 
}; 

$.plugin.method({ 
    test: 'helloworld' 
}); 

$.plugin.method({ 
    test: 'another helloworld' 
}); 

alert($.plugin.test); 
</script> 
+0

非常感謝你jhon。我現在明白了。 –