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 aFunction
object ; what is the purpose of making itsprototype
not accessible unless it is a constructor function to another variable?