Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are prototype functions different than normal functions in javascript ?

Tags:

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 ?

like image 333
Xinus Avatar asked Dec 09 '09 03:12

Xinus


People also ask

What is the difference between prototype and object in JavaScript?

A prototype is just an object. It's any object that another object uses as it's prototype.

What is prototype in JavaScript functions?

Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.

What is the difference between class and prototype in JavaScript?

Classes. The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.

What's the difference between prototype and __ proto __ in JavaScript?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.


1 Answers

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
like image 93
Igor Zevaka Avatar answered Nov 09 '22 22:11

Igor Zevaka