2017-04-27 11 views
6

मैं एक मिनी jQuery क्लोन बनाने की कोशिश कर रहा हूं जो विधि श्रृंखला का समर्थन कर सकता है। अब तक मैं कोड के इस टुकड़े के साथ आया है:jQuery ऑब्जेक्ट डेटा स्ट्रक्चर

var $ = (function() { 

    var elements = []; 

    function methodOne() { 
    console.log('Method 1'); 
    return this; 
    } 

    function methodTwo() { 
    console.log('Method 2'); 
    return this; 
    } 

    return { 
    methodOne: methodOne, 
    methodTwo: methodTwo 
    }; 
}()); 

पृष्ठ लोड पर, $ चर jQuery क्लोन Iife द्वारा दिया वस्तु के साथ आबादी वाले हो जाता है।

मेरा सवाल है, मैं विधि को चेनिंग कार्यक्षमता को बनाए रखने के दौरान $ ऑब्जेक्ट को सीधे फ़ंक्शन के रूप में कैसे कॉल कर सकता हूं?

अभी, मैं $.methodOne().methodTwo() का उपयोग कर सकता हूं लेकिन मैं jQuery की तरह $('some parameter').methodOne().methodTwo() का उपयोग नहीं कर सकता।

+0

मैंने कोशिश नहीं की है, लेकिन मुझे लगता है कि आप 'कक्षा' जावास्क्रिप्ट का उपयोग कर सकते हैं और 'एक्स्टेंड्स' एक्वाइंड्स! मुझे लगता है कि यह करेगा। आप जानते हैं, मैं उत्सुक हूं और मैं भी कोशिश करूंगा। – funcoding

उत्तर

3

var $ = function (param) { 
 

 
    var elements = []; 
 
    console.log(param); 
 

 
    function methodOne() { 
 
    console.log('Method 1'); 
 
    return this; 
 
    } 
 

 
    function methodTwo() { 
 
    console.log('Method 2'); 
 
    return this; 
 
    } 
 

 
    return { 
 
    methodOne: methodOne, 
 
    methodTwo: methodTwo 
 
    }; 
 
}; 
 

 
$('This is a param').methodOne().methodTwo();

1

Working fiddle। टिप्पणियां कम या ज्यादा आत्म व्याख्यात्मक होनी चाहिए।

यह थोड़ा लंबा लग सकता है, लेकिन यह आपको हर बार कॉल करने पर नई मिनी jQuery ऑब्जेक्ट बनाने देगा।

var _ = (function() { 

    var Magic = function(query){ 
     if(window === this) 
      return new Magic(query); 

     // reference to itself 
     var that = this; 

     //assign pseudo public methods and variables 
     that.elements = []; 
     that.methodTwo = methodTwo; 
     that.methodOne = methodOne; 

     //fills inner element array with DOM element 
     _get(query); 

     function _get(query){ 
      var elem = document.getElementById(query); 
      that.elements.push(elem); 
     } 

     function methodOne() { 
      console.log('Method 1'); 
      return that; 
     } 

     function methodTwo() { 
      console.log('Method 2', that.elements); 
      return that; 
     } 

     return this; 
    } 

    //returns function, which is assigned to a "_" variable 
    return function(query){ 
     //everytime "_" is called, it will return new instance for object Magic which makes all the work 
     return new Magic(query); 
    } 

}()); 
संबंधित मुद्दे