user979390
user979390

Reputation: 309

How should I code a jQuery plugin to use it like String.myPlugin() instead of Selector.myPlugin()?

I've been playing with jQuery lately and I need now a function for strings, and I want to execute it like this:

var str = "mystring";
if( str.myPlugin( ) )
{

}

But all the examples I found for jquery plugins can only be used like $(selector).myPlugin();If I apply them to a string i get "... is not a function".

How can I do this?

Upvotes: 0

Views: 36

Answers (2)

Kevin B
Kevin B

Reputation: 95022

When you create a string, what you are really creating is a new instance of the String object.

var str = new String("mystring");

You can add methods to all instances of the object using the object's prototype.

String.prototype.myPlugin = function(){
  alert("worky!");
}

var str = "mystring";
str.myPlugin();

Adding new methods to native objects such as the String object is usually frowned upon due to possible name conflicts.

Edit: just to add clarification.

This is not a method of jQuery and jQuery is not required to create these kinds of methods.

Upvotes: 3

Manuel van Rijn
Manuel van Rijn

Reputation: 10305

have a look at this github https://github.com/addyosmani/jquery-plugin-patterns

Upvotes: 0

Related Questions