2

I've always relied on functions but I am not trying to understand the differences between classes and functions. Are there a difference between these two in instantiating a Node? When logging them in console, they seem to log the same but I am trying to see if there's anything I am not seeing that is different.

function Node(data, left, right) {
    this.data = data;
    this.left = left;
    this.right = right;
}
let foo = new Node(55);

----------
class Node {
   constructor(data,left,right) {
      this.node = data;
      this.left = left;
      this.right = right;
   }
}
let foo = new Node(55);
burtonLowel
  • 734
  • 7
  • 17
  • 1
    No, not really. `class` is basically syntatic sugar. – Phix Apr 18 '20 at 00:47
  • 1
    Introducing `class` into the spec was more about providing a bridge to other OO languages to make it more accessible. Functionally there is no difference. – Alex D Apr 18 '20 at 00:49

1 Answers1

2

Class Syntax is basically just syntactic sugar. So it's the same. However you must invoke the class with new while you could call the Constructor Function without.

Lux
  • 17,835
  • 5
  • 43
  • 73
  • thanks @lux . How do you call the function without `new`? I tried removing `new` in my example and the variable `foo` is undefined – burtonLowel Apr 18 '20 at 00:52
  • 2
    It's undefined because the function doesn't return anything. If `function Node` had a `return` statement, then `foo` would be defined. – Alex D Apr 18 '20 at 00:54
  • You can do `const obj = {}; Node.call(obj, 55)` and then `obj.data` will be 55. – Lux Apr 18 '20 at 01:28