Well, i find this really amusing, and of course, if i were to dive into the code a little further more than this, i would of surely know how they manage to do it. What i'm talking about is JQuery library. Take a look at the code below -
$.prototype.mymethod=function(str){
alert(str);
}
//now call the added method
$(document).mymethod('hello') //alert out hello
If $
is a pure normal javascript function
(not using jquery library), the added method wont work as expected unless the new
keyword is prepended before $
new $(document).mymethod('hello')
But with JQuery, new
keyword is very optional!
Can someone give more insights into it as to how they did it without me having to go through their library?
EDIT:
After a hard struggle, finally I dug out the actual root mechanism of how the above works (constructing a
JavaScript object
without using the new
keyword)! I believe this will serve as a good futere reference for anyone desiring to learn advanved javascript!
function a(){
return a.prototype;
}
a.prototype.fn=function(){
alert('hello')
}
a.prototype.test=123;
console.log(a().test)//123
a().fn()//alerts out hello