0

coming from c family language (i use c#) makes Javascript model confusing somehow.

in c# you have to have a class. then instantiate the object from that class to use it.

in Javascript there is no class . it is all about functions. Function in itself is an object and it can be used directly without instantiating .

for example:

function sayHi(name){
alert ("hiiiii  " + name);
}

sayHi("John");

So the function sayHi is already an object and instantiated and working !!

Now if you want to access its property prototype you can do that like following:

function sayHi(name){
 alert ("hiiiii  " + name);
 }

sayHi.prototype.nn = 20;
 sayHi("John");
alert(sayHi.nn);

but the above code will fail to alert the nn as 20; it will give undefined !!

however if you make the sayHi function a constructor function to another variable then this prototype property will be accessable like the followin:

 function sayHi(name){
     alert ("hiiiii  " + name);
     }

    sayHi.prototype.nn = 20;
     sayHi("John");
    alert(sayHi.nn);

var hi2 = new sayHi("May");
alert(hi2.nn);

now alert(hi2.nn) give you 20 ; which means the prototype of the sayHi was not accessible till we instantiate it using the word new assigning it to another variable.

My question:

  • Isn't this similar to the c# class instantiation?
  • and since the function sayHi is already a Function object ; what is the purpose of making its prototype not accessible unless it is a constructor function to another variable?

CODE DEMO

stackunderflow
  • 3,811
  • 5
  • 31
  • 43
  • I would suggest you to look through the related questions section. I think you are misunderstanding the `.prototype` usage. – Artyom Neustroev May 30 '14 at 10:46
  • http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work?rq=1 – stackunderflow May 30 '14 at 11:26
  • Maybe the following explanation helps: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR May 30 '14 at 23:37
  • Till today, all explanations I read are lengthy convoluted that can't stands on its own, you will have to use another convoluted explanation to clarify the first one. – stackunderflow May 31 '14 at 13:37

0 Answers0