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....
}
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....
}
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");
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.