1

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

1 Answer 1

3

From the source code :

jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
},

The new is already called when you call $(document).

If you want to do the same thing the jQuery way, here's how it can be :

var A = function(str){
    return new A.prototype.init(str);
}
A.prototype.init =function(str){
     this.str = str;
     return this;
};
A.prototype.init.prototype = A.prototype;

A.prototype.f = function(arg){ // add your function
   console.log(this.str+' '+arg);
};
A('hello').f('world'); // logs "hello world"
A('bye').f('bye'); // logs "bye bye"
Sign up to request clarification or add additional context in comments.

8 Comments

@spaceman12: There is nothing special about it. Just create a function which, when called, creates a new object and returns it. For example: function A() { return new B(); }.
But if i want to add method to A and not B, and call it as A().mymethod() , how would you return the new created object for A?
Wouldn't A().mymethod() call mymethod on whatever is returned by A, not A itself? I think it you want to return a new object for A you would need A.mymethod(), which will return a new created object for A if mymethod creates one...
@spaceman12: If you want to create a new instance of A without calling new, have a look at this question. Note though that this is not what jQuery is doing.
@spaceman12: The "problem" with your solution is that you are always returning the same object. You won't be able to access any arguments passed to a as function.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.