We can use a Javascript function as "Class". For example:
function Test()
{
this.key1 = "JKLDSJKLFJDSKLJFLKSJFKLDSJFLJKDSLFJKDLSJFK";
this.method1 = function()
{
var a = "DJKLJFKSDLFLKSD";
var b = new Date();
return a+b.toString();
}
}
In this case, each time when we create a new instance of Test, the javascript engine will run the content of the Test function and define the methods and properties. If we create 10000 instances of Test, the engine will create 10000 "key1" properties and 10000 "method1" methods.
But we can put the properties and methods to the Test function's prototype. When we create instances of Test, javascript engine will not re-define the properties and methods, but the properties and methods defined on prototype is still accessable by "this". This works just like the parent class for other languages.
function Test()
{
}
Test.prototype.key1 = "JKLDSJKLFJDSKLJFLKSJFKLDSJFLJKDSLFJKDLSJFK";
Test.prototype.method1 = function()
{
var a = "DJKLJFKSDLFLKSD";
var b = new Date();
return a+b.toString();
};
Now, let's do some test to check which one is better. Here I use nodejs( V8 engine ) to create 10,000 instances of the Test function and see the memory used by the instances.
For method 1 ( defines properties and methods inside the function ), it uses about 1.5MB memoery. For method 2, it only uses about 800KB.
Now you know how to define a frequently used "Class" in Javascript.
-- END --