1

I understand what the difference is between a function expression and a function declaration but how are they different when it comes to the reference of a class? Like where can the below someFunction be used inside the class and where can it not? Which class can be instantiated where?

class xyz {
    someFunction(){
        // Function code
    }
}

vs

class xyz {
    var someFunction = function(){
        // Function code
    }
}
0

2 Answers 2

3

When you use a function declaration, the function goes to the class prototype.

class xyz {
    someFunction(){
        // Function code
    }
}

The above class can be represented as function constructor:

    function xyz() {
        //Code.
    }
    xyz.prototype.someFunction = function() {
      //Some code
    }

So someFunction() will be part of xyz's prototype.

Function expressions throws invalid syntax error when you use them in a class. But when you use a function expression in classic function constructors, the function is just a local variable and cannot be accessed by xyz instances.

function xyz()
 {
    var someFunction = function(){
        // Function code
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

This case has nothing to do with the difference between a function expression and a function declaration

you will get Unexpected identifier because docs doesn't allow or define such syntax

class xyz {
    var someFunction = function(){
        // Function code
    }
}

In class syntax,you have three choices to write function:

class xyz {
  constructor() {
    // Function code
  }
  someFunction() {
    // Function code
  }
  static sayHi() {
    // Function code
  }
}

If you use other expressions or statements not allowed by docs,you will get error

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.