2016-09-07 6 views
4

JQueryは$を関数として扱っていますが、私は知りたいのですが、どうすればそのような関数を作ることができますか?

JavaScriptで請負業者機能を使用するにはどうすればよいですか? のように、私はこれます(例)

window.test = (function() {   
    var test = { 
     get: function (selector) { 

     } 
    }; 

    return test; 
}()); 

を私は直接、私はあなたがこの連鎖オブジェクトと同じように必要だと思うtest()

答えて

4

を呼び出すときにcanvas要素を選択します。

var myQuery = function (str) {  
 
    this.str=str; 
 
    this.concate = function(str){ 
 
    this.str= this.str+" "+str; 
 
    return this; 
 
    }; 
 
    this.to_string = function(){ 
 
    return this.str; 
 
    }; 
 
    return this; 
 
}; 
 
window['$']=myQuery; 
 

 
alert($('hello').concate(' $').concate('!!').to_string()); 
 
alert(myQuery('hello').concate('myQuery').concate('!!').to_string());

別のシナリオ:直接$へMYQUERYの宣言参照。

var myQuery = (function (str) {  
 
    if(typeof window['$'] ==="undefined") 
 
    { 
 
    \t window['$']=this; 
 
    } 
 
    this.str=str || ''; 
 
    this.concate = function(str){ 
 
    this.str= this.str+" "+str; 
 
    return this; 
 
    }; 
 
    this.to_string = function(){ 
 
    return this.str; 
 
    }; 
 
    return this; 
 
})(); 
 

 
alert($.concate("From $").to_string());

+0

を実装します... –

+0

素敵な答え!これは 'myQuery'関数内の' window ['$'] = myQuery'を作ることができませんか?すぐに呼び出された関数を使うのと同じです! – M98

+0

@Kermani、申し訳ありません、私はあなたを取得しませんでした..私はいくつかの変更を行って...あなたはそれについて話している? –

2

above answerは正しいですが、私はあなたが必要なものを理解すると思うし、多分この答えはまた、あなたを助ける:連鎖するオブジェクトを

window["$"] = function (selector) {  
 
    this.s=selector; 
 
    this.changeColor = function(color){ 
 
     document.getElementById(this.s).style.background = color; 
 
    return this; 
 
    }; 
 
    return this; 
 
};
<div id="elementId"> 
 
    Change my background. 
 
</div> 
 

 
<a onClick="$('elementId').changeColor('red');" href="#">Red</a> 
 
<a onClick="$('elementId').changeColor('blue');" href="#">Blue</a> 
 
<a onClick="$('elementId').changeColor('green');" href="#">Green</a>

+0

あなたの答えをありがとう、それは有用ですが、あなたが言ったように、私は上記の答えがより完全だと思う...ありがとう –

+0

@ Lash2ようこそ:) – M98

+0

@ Kermani 、偉大な..あなたはラッシュ2が必要なものを達成しました.. !!! :) –

関連する問題