Suresh Kamrushi
Suresh Kamrushi

Reputation: 16086

Javascript oops: defining function with or witout prototype

Below is my class:

function myfunc(){
    // some code
}

1) declaring a method/function of a class

myfunc.getInstance = function(){
          // some code
};

Or alternatively i can define like below:

myfunc.prototype.getInstance = function(){
    // some code
};

Please tell me what is the difference between defining method/function with or without prototype.

Upvotes: 1

Views: 98

Answers (2)

Suraj Sharma
Suraj Sharma

Reputation: 180

with

myfunc.prototype.getInstance = function(){ // some code };

if you create any object that inherits myfunc, it will be able to access getInstance method with prototype chain. the new object's __ proto __ will point to prototype of its parent i.e myfunc's

with

myfunc.getInstance = function(){
      // some code};

getInstance method cannot be inherited and hence only myfunc is able to call it not the objects which inherits it.

example

function myfunc(){

}

myfunc.getInstance = function(){
    console.log("I can be invoked only by myfunc")
}

myfunc.prototype.getInstance2 = function(){
    console.log("I can be inherited and called by other objects too")
}

let newobj = new myfunc();

newobj.getInstance2();

// I can be inherited and called by other objects too


newobj.getInstance();
// Uncaught TypeError: newobj.getInstance is not a function

myfunc.getInstance();
// I can be invoked only by myfunc

Upvotes: 1

Parthik Gosar
Parthik Gosar

Reputation: 11646

Prototype functions are meant to be called on an object of class (like a normal class in OOPs). Where as normal functions can be called directly on the class (like a static class in OOPs).

function Foo ()
{
}

//Should be called through Foo.SayHello()
Foo.SayHello = function ()
{

}


/*
Should be called on the object of Foo
var MyObject = new Foo();
MyObject.SayHello();
*/

Foo.prototype.SayHello = function ()
{
}

Upvotes: 0

Related Questions