Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any technical difference between these methods? [duplicate]

Tags:

javascript

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?

like image 865
RuntimeException Avatar asked Mar 17 '26 13:03

RuntimeException


1 Answers

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.

like image 75
Zeta Avatar answered Mar 20 '26 01:03

Zeta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!