0

How to write my own functions similar to jquery? For example:

$('parameter1').doSomething('parameter2);

function $(p1){
   var doSomething=function(p2){}; // this does not work to call....

}
Martin G
  • 17,357
  • 9
  • 82
  • 98
kaf
  • 41
  • 7
  • What is `parameter1` ? , what is `parameter2` ? , what is expected result ? See http://stackoverflow.com/questions/1991126/difference-between-jquery-extend-and-jquery-fn-extend – guest271314 Jul 01 '15 at 01:57
  • I wanted to write like jquery: $("any parameter").action("second parameter); How do i write this to work in JS (no Jquery)? Thank you. – kaf Jul 02 '15 at 15:07
  • See https://github.com/jquery/jquery/blob/master/src/jquery.js , https://github.com/jquery/jquery/blob/master/src/core/init.js – guest271314 Jul 03 '15 at 01:12
  • i saw it but still does not seem what i want. The define function is part os RequireJS. Not standard JS. – kaf Jul 03 '15 at 06:07

2 Answers2

1

Try defining $ as property of global window object ; creating an object obj within $() function having property doSomething , setting window.$ to object obj ; creating an alias for window.$ utilizing a namespace; return window.$ object having property .doSomething from call to $()

window.$ = function $(args) {
  var obj = {
    doSomething: function doSomething(args) {
      // do stuff
      document.write(args + "\n");
      console.log(this);
      // return `window.$`
      return window.$
    }
  };
  // create alias for `window.$`
  var namespace = "abc";
  // set `window.$` to `obj`
  window.$ = window[namespace] = obj;
  if (args && window.$) {
    window.$.doSomething.call(window.$, args)
  };
  // return `window.$`
  return window.$
};

$("abc").doSomething("def");
guest271314
  • 1
  • 15
  • 104
  • 177
0

First you'll need to understand the concept of method chaining in JavaScript.

Your $() method in the example above doesn't return anything.

Even if it did, the object returned from your $() method would also need to have a doSomething() method.

For example:

$ = function(id) {
    return document.getElementById(id);
}

$('foobar').doSomething(); //assumes doSomething() exists on the returned object.
arthurakay
  • 5,631
  • 8
  • 37
  • 62