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
}
}
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
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.