1

When I research online, I'm finding different answers.

class Foo {
    constructor() {
        this.data = [];
    }

    add(x) {
        //
    }
}

Is the above code equivalent to Code A or Code B?

Code A:

function Foo() {
    this.data = [],
    this.add = function(x) {
        //
    }
}

Code B:

function Foo() {
    this.data = []
}

Foo.prototype.add = function(x) {
    //
}
halfer
  • 19,824
  • 17
  • 99
  • 186
gjvatsalya
  • 1,129
  • 13
  • 29

1 Answers1

2

Code B in your example, here is an example taken from https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes

class Animal { 
  speak() {
    return this;
  }
  static eat() {
    return this;
  }
}

let obj = new Animal();
let speak = obj.speak;
speak(); // undefined

let eat = Animal.eat;
eat(); // undefined

is the same as

function Animal() { }

Animal.prototype.speak = function(){
  return this;
}

Animal.eat = function() {
  return this;
}

let obj = new Animal();
let speak = obj.speak;
speak(); // global object

let eat = Animal.eat;
eat(); // global object

Be aware this is using ES6 notation and is not fully supported at time of writing. See here for what supports ES6 - https://kangax.github.io/compat-table/es6/

andy mccullough
  • 9,070
  • 6
  • 32
  • 55
  • Very small but potentially important nitpick: class declarations in ES6 proper are *not* hoisted, but functions (and therefore class declarations that have been transpiled back to ES3-5) *are* hoisted. – ssube Nov 16 '16 at 15:22