Ok I should know the answer to this but for some reason I have never really understood or had the need to really get to know JavaScript.
My question is: Looking at the code samples below am I correct in my understanding or am I missing some information.
Sample 1
Need to instantiate the function (or class) in order to use the IsOld
method, and a separate copy of the IsOld
function will be created for each instance.
function MyClass1() {
this.IsOld = function (age) {
if (age > 40) {
return true;
}
return false;
};
}
// sample usage
var m1 = new MyClass1();
console.log(m1.IsOld(34));
Sample 2
Need to instantiate but unlike MyClass1
the scripting engine will not need to create a copy of the method IsOld
for each class instance.
var MyClass2 = (function () {
function MyClass2() { }
MyClass2.prototype.IsOld = function (age) {
if (age > 40) {
return true;
}
return false;
};
return MyClass2;
})();
// sample usage
var m2 = new MyClass2();
console.log(m2.IsOld(34));
Sample 3
No need to instantiate the function / class to access the IsOld
method. A single instance of the IsOld
method is used across all invocations.
var MyClass3 = {
IsOld: function (age) {
if (age > 40) {
return true;
}
return false;
},
};
// sample uage
console.log(MyClass3.IsOld(34));
Note: I am guessing there are plenty of similar question / answers here on SO but for some reason I could not find one that actually made sense to me.
Your understandings seems to be correct.
If by "need to instantiate" you mean use of 'new' keyword, I'd like to add something here.
In JavaScript use of new keyword is not the only way to create new instances. (Edited as per comments) And any function can act as a constructor function.
When you use 'new' keyword followed by any function (say 'x') what it does is
Here is a good source for you to learn JavaScript by Douglas Crockford (http://javascript.crockford.com/)
So, if you are concerned about the memory (you should be), use a constructor function, and add all the common methods to functions prototype like you have done in Sample 2.
Then all those methods will be inherited to all the objects created using this function as the constructor. However, as mentioned before I think Sample 2 can be simpler:
var MyClass2 = function MyClass2() { };
MyClass2.prototype.IsOld = function (age) {
if (age > 40) {
return true;
}
return false;
};
var obj = new MyClass2();
As far as I know, you're right in all 3 cases.
IsOld
and for every instance there will be new function created.IsOld
as it is in prototype.IsOld
as MyClass3 is already an instance (an object not a function).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With