Xinus
Xinus

Reputation: 30513

How are prototype functions different than normal functions in javascript ?

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 ?

Upvotes: 7

Views: 1671

Answers (3)

Justin Johnson
Justin Johnson

Reputation: 31300

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)

Upvotes: 0

Igor Zevaka
Igor Zevaka

Reputation: 76510

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

Upvotes: 16

Matt
Matt

Reputation: 44058

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

Upvotes: 7

Related Questions