termi / es6-transpiler

Tomorrow's JavaScript syntax today
Other
216 stars 18 forks source link

Bug with class constructor #58

Closed yernende closed 10 years ago

yernende commented 10 years ago

Class instance doesn't get methods, if constructor returns an object for initialization:

class Character {
  constructor() {
    return {
      hp: 10
    }
  }

  hit(damage) {
    this.hp -= damage;
  }
}

var character = new Character();
character.hit(10); //TypeError: undefined is not a function

Or it is a feature?

SerkanSipahi commented 10 years ago

hi, you do it wrong !

this working( look at a the constructor. You can compare it with mine.

class Character2 {
    constructor() {
        this.hp = 0; // set your props here ! do not return object/s from the constructor if not necessary
    }
    hit(damage) {
        this.hp -= damage;
    }
}

var character = new Character2();
console.log(character.hit(10));
console.log(character);

i hope i could help you :)
@bitcollage
yernende commented 10 years ago

Hi. Yes, thanks, I know about this way and know that it works, but constructing by returning of object is also correct, at least in the ES5.

Nevertheless, this ES5 code throws a error "character.hit is not a function", too:

function Character() {
  return {
    hp: 0
  }
}
Character.prototype = {
  hit: function(damage) {
    this.hp -= damage;
  }
}

var character = new Character();
console.log(character.hit(10))

So, it seems it is a feature.