Ajay Gaur
Ajay Gaur

Reputation: 5270

Difference between two types of function declaration in javascript inside a class?

I've been working in React and Redux for past 2 years but when I was using inheritance in javascript, I found the difference between these 2 type of function declaration in javascript.

I've the class a and a class b which inherits from class a and whenever I'm running the following snippet, it logs out

bfunc called from class a
afunc called from class b

I assume that the syntax bfunc = function(){ puts the function in this and the syntax afunc() { puts the function in the prototype of class but I'm not really sure. Can someone please explain this behaviour?

class a {
  afunc() {
    console.log('afunc called from class a');
  }

  bfunc = function() {
    console.log('bfunc called from class a');
  }
}

class b extends a {
  afunc() {
    console.log('afunc called from class b');
  }

  bfunc() {
    console.log('bfunc called from class b');
  }
}

const bObject = new b();
bObject.bfunc();
bObject.afunc();

bfunc called from class a
afunc called from class b

Upvotes: 2

Views: 57

Answers (2)

Dabbas
Dabbas

Reputation: 3230

As @Barmar said in his answer, and in details:

Using babel this is what your code's transpiled to: [Follow the link].

If you beautified the transpiled version of the code you'll notice that defining a function like:

  bfunc = function() {
    //
  }

Will a add the function to this.
While:

  bfunc() {
    //
  }

Will be added to the prototype it self:

b.prototype.bfunc = function () {
    //do something
};

Take a look here for more details on why calling bfunc using this will take precedence over prototype.

Upvotes: 2

Barmar
Barmar

Reputation: 780974

Your assumption is correct. If you do console.log(bObject); you'll see that it has its own bfunc property that contains the function.

Since the prototype is only used when the object doesn't have its own property, this takes precedence even though it was put in by the parent class.

Upvotes: 3

Related Questions