7

Javascript functions can be declared on a objects prototype like this:

<object name>.prototype.<variable name>=function(){
//
//
}

How it this different than following declaration?

<object name>.<variable name>=function(){
//
//
}

How are prototype functions different than normal functions in javascript ?

ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78
Xinus
  • 29,617
  • 32
  • 119
  • 165
  • 1
    Please re-phrase into a real question that can be answered. – gahooa Dec 09 '09 at 03:10
  • 3
    @gahooa: Why do you think this question can't be answered. It might be very high level, but it is still a question. You can always edit it to make it more clear. No need to down vote this simply because of grammatical mistakes... – Josh Dec 09 '09 at 03:13
  • http://stackoverflow.com/questions/186244/what-does-it-mean-that-javascript-is-a-prototype-based-language – John Paulett Dec 09 '09 at 03:13
  • Some doggone good stuff here: http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript/1598077#1598077 – Crescent Fresh Dec 09 '09 at 03:17

3 Answers3

16

Prototype functions are instance functions, whilst normal functions are "static" functions. Functions declared on class's prototype will available on all instances of that class.

var MyClass = function(){
};
MyClass.staticFunction = function(){alert("static");};
MyClass.prototype.protoFunction = function(){alert("instance");};

MyClass.staticFunction(); //OK
MyClass.protoFunction (); //not OK

var myInstance = new MyClass ();
myInstance.staticFunction(); //not OK
myInstance.protoFunction (); //OK
Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
7

functions declared on a base object's prototype are inherited by all instances of that object type.

For example..

String.prototype.foo = function () {
  return 'bar';
};

Now, every string will have the function foo() available.

'test'.foo(); // returns 'bar'

Read more about prototype-based inheritance here

Matt
  • 43,482
  • 6
  • 101
  • 102
  • 2
    +1 Also, it is worth explicitly stating that functions *and properties* declared on an object's prototype are inherited by all instances of the that object, *even those that have already been instantiated.* – Justin Johnson Dec 09 '09 at 03:33
  • Yes, good point. That last part is very important. The prototype acts somewhat as the last catch before a member is considered 'undefined' .. so modifying the prototype affects existing objects too. – Matt Dec 09 '09 at 03:36
0

Matt and Igor have already provided enough code samples, but one of the best articles (short, correct and to the point) that you can read is Prototypal Inheritance, by Douglas Crockford.

There are also lots of different ways to facilitate inheritance through popular libraries (Dojo, Prototype, etc)

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89