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 ?

4
  • 1
    Please re-phrase into a real question that can be answered. Commented Dec 9, 2009 at 3: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... Commented Dec 9, 2009 at 3:13
  • stackoverflow.com/questions/186244/… Commented Dec 9, 2009 at 3:13
  • Some doggone good stuff here: stackoverflow.com/questions/1595611/… Commented Dec 9, 2009 at 3:17

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

+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.
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.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.