3

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?

RuntimeException
  • 1,135
  • 2
  • 11
  • 25

2 Answers2

1

In your code, a is a function of the instance, whereas b is a function of the class.

In terms of them actually working, there isn't much different between them by themselves. However, let's say you put var test = 123; inside the obj function. a will be able to access it, but b will not.

Additionally, you can overwrite instance.a with another function, and it will only affect the current instance.

On the other hand, a is a separate function object for each instance of the object. This could become a problem in terms of memory use if you have large numbers of instances.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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.

Zeta
  • 103,620
  • 13
  • 194
  • 236