Paul
Paul

Reputation: 6176

"prototype" in jQuery fn? + plain javascript code inside a jquery function?


i was wondering what prototype means in jQuery? i usually find infos about "Prototype" - the framework - but here it's "prototype" inside jQuery...? Could you please tell me when it's best to use it?

Also, could you tell me : why do we use a "plain javascript" code inside a jQuery plugin, instead of the jquery code, like in this example? is it a rapidity issue?

here's my example : (a plugin for twitter)

Thanks for your answers !

$.each(data, function(i, item) {  
    holder.append("<p>"+item.text.makeLinks()+"</p>");  
});  
//...further in the code  
String.prototype.makeLinks = function() {  
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/,   function(str) {  
        return str.link(str);  
    });  
};  

Upvotes: 14

Views: 20013

Answers (2)

Ortiga
Ortiga

Reputation: 8824

Prototype is a pure javascript functionality.

It's used to add properties or methods to an already defined object (somewhat like extending). For example:

function myCustomObject(){
}

myCustomObject.prototype.myCustomAttr = "Hello";

var instance = new myCustomObject();

alert(instance.myCustomAttr); // alerts Hello

Upvotes: 11

Matt Ball
Matt Ball

Reputation: 359966

I was wondering what "prototype" means in jQuery

The JavaScript library named Prototype takes its name from the JavaScript prototype. In JavaScript, the prototype is the mechanism which provides inheritance (as opposed to, say, classes). Example:String.prototype refers to the prototype object of Strings, which contains (among other things) methods which can be invoked on any String.

In the example in your question, the twitter plugin creates a new function on String.prototype, called makeLinks, which allows for function calls such as:

text.makeLinks()

where text is a string.

More reading on prototypes:


Why do we use a "plain javascript" code inside a jQuery plugin, instead of the jQuery code?

jQuery is not a replacement for JavaScript. It is a JavaScript library, meant to make it easier to write JavaScript which would otherwise have to use the DOM API. You see "vanilla" JavaScript in the jQuery plugin because there's really no better way to do what that JS does.

jQuery is JavaScript. It simplifies writing other JavaScript by providing a simpler API which remains consistent across browsers. This is not the case with the DOM, because the various browser vendors have created DOM APIs which are mostly the same, but not identical.

Quirksmode is a site popular for documenting these inconsistencies (in CSS as well as in JavaScript).


Welcome to web development!

Upvotes: 42

Related Questions