It seems to me that there has been some misunderstanding regarding the structure of the class and the dynamic nature of Javascript: for all the cases presented, each instance of the class creates a new unnamed function.
If you want to declare “classes” in a more traditional way (like C ++ or Java), you'd better:
1) Define the functions:
function MyClass_IsOld(age) { return (age > 40); }
2) Create a "class" and define its prototype:
function MyClass() { }; MyClass.prototype.IsOld = MyClass_IsOld;
3) Use the class:
var myInstance = new MyClass(); console.log(myInstance.IsOld(37));
If you want to use the "method" as a regular function, declare it globally, for example:
function MyClass_IsOld(age) { return (age > 40); } function MyClass() { }; MyClass.prototype.IsOld = MyClass_IsOld; var myInstance = new MyClass(); console.log(myInstance.IsOld(37));
If you want to hide implementation details, create a closure:
var MyClass = (function () { function _MyClass_IsOld(age) { return (age > 40); } function _MyClass() { }; _MyClass.prototype.IsOld = _MyClass_IsOld;
source share