Rodney Carvalho
Rodney Carvalho

Reputation: 21

Javascript prototype inheritance doesn't call expected method

Why does this print out 'bye' instead of 'hello'? According to the inheritance chain as is described in this blog post, I would've thought it would log 'hello'.

http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/

class Test {
  hello() {
    console.log('hello')
  }
}

Test.prototype.hello = function(){
  console.log('bye')
}

const t = new Test
t.hello()

Upvotes: 1

Views: 34

Answers (1)

theprogrammer
theprogrammer

Reputation: 2734

You are rewriting the definition of hello on the "prototype". When you do class Test () ... hello is the equivalent of

Test.prototype.hello

The class syntax is mostly sugar on top of the normal prototypical definition of a function.

Upvotes: 3

Related Questions