I have been trying to learn OO JS. I was playing with different patterns, wrote following example.
var obj = function() {
this.a= function() {
return 'a';
}
}
obj.prototype.b = function() {
return 'b';
}
var instance = new obj();
console.log(instance.a());
console.log(instance.b());
Is there any difference here in function a and b?
this.a will be a separate function for every object you create:
var obj = function() {
this.a= function() {
return 'a';
}
}
obj.prototype.b = function() {
return 'b';
}
var instance1 = new obj();
var instance2 = new obj();
console.log(instance1 === instance2); // false: different instances
console.log(instance1.a === instance2.a); // false: different functions (this.a)
console.log(instance1.b === instance2.b); // true: obj.prototype.b
This means that this.a = function(){ ... } will consume memory for every instance, something you most likely want to avoid.
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