简体   繁体   English

类中的函数表达式

[英]Function expression in a Class

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? 我知道function expressionfunction declaration之间的区别是什么,但是在引用类时它们有何不同? Like where can the below someFunction be used inside the class and where can it not? 像下面的someFunction可以在类中的什么地方使用? Which class can be instantiated where? 哪个类可以在哪里实例化?

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

vs 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. 因此someFunction()将成为xyz原型的一部分。

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. 但是,当您在经典函数构造函数中使用函数表达式时,该函数只是局部变量,无法被xyz实例访问。

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 您将获得Unexpected identifier因为文档不允许或定义此类语法

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

In class syntax,you have three choices to write function: class语法中,您可以选择三个函数来编写函数:

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 如果您使用其他文档不允许的表达式或语句,则会出现错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM