kqhasaki
kqhasaki

Reputation: 31

A really confusing thing about JavaScript methods

class Boy {
  sayName = function() {
    console.log('You should rewrite this method!')
  }
  sayName2 = function() {
    return
  }
}

class BabyBoy extends Boy {
  sayName() {
    console.log('I have rewritten this method!')
  }
}

var babyBoy = new BabyBoy()

babyBoy.sayName() // here it outputs: You should rewrite this method!

How did it happen?? It's been bugging me for hours! It seems that there exists some difference between method() and method = function(){}.

Upvotes: 2

Views: 61

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

Let's "desugar" your code a bit by creating explicit constructor functions (which classes basically are under the hood) and moving public class field definition to the constructor

class Boy {
  constructor() {
    // move public fields to constructor
    this.sayName = function() {
      console.log('You should rewrite this method!')
    }
  }
  
  // define prototype method
  prototypeMethod() {}
}

class BabyBoy extends Boy {
  // add explicit construtor
  constructor() {
    // that calls super
    super()
  }

  sayName() {
    console.log('I have rewritten this method!')
  }

  // override prototype method
  prototypeMethod() {}

}

var babyBoy = new BabyBoy()
var anotherBabyBoy = new BabyBoy()

// lets first ensure that every instance has its own properties
console.log(`babyBoy.sayName === anotherBabyBoy.sayName is ${babyBoy.sayName === anotherBabyBoy.sayName}`)

// check that it doesn't come from prototype
console.log(`babyBoy.sayName === BabyBoy.prototype.sayName is ${babyBoy.sayName === BabyBoy.prototype.sayName}`)

// then make ensure that every instance shares the same method from prototype
console.log(`babyBoy.prototypeMethod === anotherBabyBoy.prototypeMethod is ${babyBoy.prototypeMethod === anotherBabyBoy.prototypeMethod}`)

// check that it comes from prototype
console.log(`babyBoy.prototypeMethod === BabyBoy.prototype.prototypeMethod is ${babyBoy.prototypeMethod === BabyBoy.prototype.prototypeMethod}`)

Upvotes: 1

Related Questions