mrblah
mrblah

Reputation: 103607

what exactly does the keyword prototype do in jquery?

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?

Upvotes: 6

Views: 1227

Answers (2)

Marc W
Marc W

Reputation: 19251

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.

Upvotes: 5

Jonathan Fingland
Jonathan Fingland

Reputation: 57177

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");

Upvotes: 12

Related Questions