Two classes are defined below: ClassA and ClassB , which have equal functionality but are different in nature:
function ClassA(name){ this.name = name; // Defines method ClassA.say in a particular instance of ClassA this.say = function(){ return "Hi, I am " + this.name; } } function ClassB(name){ this.name = name; } // Defines method ClassB.say in the prototype of ClassB ClassB.prototype.say = function(){ return "Hi, I am " + this.name; }
As shown below, they are not much different in use, and they are both “methods”.
var a = new ClassA("Alex"); alert(a.say()); var b = new ClassB("John"); alert(b.say());
So, what do you mean by “function”, according to the msdn link you gave as a comment, it seems that the “function” is just a “static method”, like in C # or Java?
// So here is a "static method", or "function"? ClassA.createWithRandomName = function(){ return new ClassA("RandomName"); // Obviously not random, but just pretend it is. } var a2 = ClassA.createWithRandomName(); // Calling a "function"? alert(a2.say()); // OK here we are still calling a method.
So this is what you have in your question:
var johnDoe = { fName : 'John', lName: 'Doe', sayHi: function() { return 'Hi There'; } };
OK, this is an Object , but obviously not a class.
source share