1

I DO NOT WANT TO CREATE A JQUERY PLUGIN

Let's say I have something like this:

// In folib.js
function Foo() {this.Prop = function() {//do something}};

So my users can reference my JavaScript library and instantiate my object all day

// In consumer
foo = new Foo();
alert(foo.Prop);

Now, I want to create a JQuery like plugin system for my class, whereas I can create plugin script libraries which extend Foo().

I think I should be doing something like this...

(function( foo ){
    foo.myPlugin = function() {  
       // Do your awesome plugin stuff here
    };
})(Foo);

But I can't get that working. Any ideas on how this is done in JQuery? I can't figure it out :(

1
  • OK, follow me here...I'm thinking I need to do something like function Foo() {this.fn = function(script) {this.prototype.script;}}; Commented Apr 5, 2011 at 0:11

2 Answers 2

5

Using prototype:

Foo.prototype.myPlugin = function () { /* Do plugin stuff */ };

Then you will be able to access the plugin like so:

var foo = new Foo();
alert(foo.myPlugin);

Prototypes work when used in conjunction with new: the new object (foo) has a hidden pointer to the prototype object of the function it was constructed from (Foo). If a property isn't found on the new object, JS will search for it in the prototype. For more information, read this.

jQuery does a similar thing by providing a fn property which points to prototype:

Foo.fn = Foo.prototype;
Sign up to request clarification or add additional context in comments.

Comments

3

To follow up on Box9's great answer, you should also return the object on which you are performing the action.

Foo.prototype.myPlugin = function () { 
     /* Do plugin stuff */ 

     return this; //return the object's instance
};

This will enable you to chain functions modifying the same object. This is part of what makes jQuery so popular--it uses a fluent interface which allows for more expressive syntax when chaining functions and plugins. http://en.wikipedia.org/wiki/Fluent_interface

This maybe not be what you were asking for, but it is particularly helpful when creating many functions extending an object.

myFooInstance.DoSomething(5).DoAnotherThing('hello').YetAnother();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.