views:

68

answers:

2

Is the keyword (or method?) prototype in jquery kind of like extension methods?

i.e. all classes will have this functionality available to it going forward?

+6  A: 

This is part of javascript and not specific to jquery.

the prototype property defines methods and properties shared by all objects of that type.

e.g.

function MyClass()
{
}

myClass.prototype.myMethod = function()
{
    alert("hello world");
}

var myObject = new MyClass();
myObject.myMethod();

All instances of MyClass will have (share) the method myMethod().

Note that methods on the prototype do not have the same visibility as methods declared within the constructor.

For example:

function Dog(name, color)
{
    this.name = name;

    this.getColor = function()
    {
        return color;
    }
}

Dog.prototype.alertName = function {
    alert(this.name);
}

Dog.prototype.alertColor = function {

    //alert(color);  //fails. can't see color. 
    //alert(this.color); //fails. this.color was never defined

    alert(this.getColor()); //succeeds
}

var fluffy = new Dog("Fluffy","brown");
Jonathan Fingland
+3  A: 

prototype is not a jQuery keyword; it is a Javascript keyword. It is used to add public functions to objects in a way such that they will exist every time you create a new instance of that object.

Marc W
http://meta.stackoverflow.com/search?q=lmgtfy
Robert Harvey