为什么我的ES6(使用Babel)类说“ this”在实例方法中未定义?

布伦南

我正在使用Hapi.JS在Node中构建应用程序。

我有一个用于身份验证插件的类,它给我带来各种各样的问题。当我尝试this从类的方法中进行引用时,出现一条错误消息,this即未定义。为什么会这样呢?

摘录:

class OAuth {

  constructor () {}

  register (server, err, next) {
    this.server = server;
    this.registerRoutes();
  }

  registerRoutes () {
    console.log(this.server.route);
    this.server.route([
      {
          method: 'POST',
          path: '/oauth/token',
          config: {
              auth: false,
              handler: function(request,reply){
                console.log("test");
                reply("test");
              }
            }
      },
      {
        method: 'GET',
        path: '/test',
        config: {
          auth: false,
          handler: function(request,reply){
            console.log("test");
            reply("test");
          }
        }
      }
    ]);
  }
}
module.exports = new OAuth();

在其他地方,这称为:

const oauth = require('./oauth');
oauth.register(server);

每次调用寄存器函数时,都会收到此错误:

TypeError: Cannot set property 'server' of undefined

为什么我的实例不起作用?

创意手柄

带有babel的ES6类不会this为您自动绑定class引入以来这是一个普遍的误解有多种解决方法。

  1. 使用ES7。Babel有一个实验性的(截至本文)类属性插件。

    class OAuth {
      constructor () {}
    
      register = (server, err, next) => {
        this.server = server
        this.registerRoutes()
      }
    
      registerRoutes = () => {}
    }  
    

这是如何运作的?当您将箭头功能与class-properties插件一起使用时,它会转换为如下所示的内容,并在您使用class语法时按预期进行绑定

var OAuth = function OAuth() {
  var _this = this;

  _classCallCheck(this, OAuth);

  this.register = function (server, err, next) {
    _this.server = server;
    _this.registerRoutes();
  };

  this.registerRoutes = function () {};
}
  1. 将类属性绑定到构造函数中

    class OAuth {
      constructor () {
        // `this` is the OAuth instance in the constructor
        this.register = this.register.bind(this)
        this.registerRoutes = this.registerRoutes.bind(this)
      }
    
      register (server, err, next) {
        // `this` is the global object.. NOT! 
        // after binding in the constructor, it's the OAuth instance ^_^
        // provided you use `new` to initialize your instance
        this.server = server
        this.registerRoutes()
      }
    
      registerRoutes () {}
    }
    
  2. 使用createClassfrom react,它将为您完成绑定。注意,我们仅将react用于其class属性绑定魔术。我们没有创建反应组件。

    import React from 'react'
    
    const OAuth = React.createClass({
      register (server, err, next) {
        this.server = server
        this.registerRoutes()
      }
    
      registerRoutes () {}
    })
    
  3. autoBindreact-class中使用在这里,我们使用ES6 +类语法制作了一个react组件,只是为了使用该autoBind方法。我们没有用componentWillMountrender等,其提供有反应的组分。

    import { autoBind } from 'react-class'
    
    class OAuth extends React.Component {
      constructor(props) {
        super(props)
        autoBind(this)
      }
    
      register (server, err, next) {
        this.server = server
        this.registerRoutes()
      }
    
      registerRoutes () {}
    }
    
  4. 滚动自己的类属性绑定器。这是一个很好的练习,基本上与选项2相同,也可能更少的代码。

    // call it in your constructor
    bindStuff(this, ['register', 'registerRoutes', 'etc'])
    
    // define it somewhere as
    function bindStuff (context, props) {
      props.forEach(prop => {
        context[prop] = context[prop].bind(context);
      })
    }
    
  5. 如果您确实想创建React组件,则可以结合使用箭头功能和属性初始化程序来执行以下操作

    class OAuthComponent extends React.Component {
      whateverMethodYouWant = (event) => {
        this.setState({somePropertyYouCareAbout: true}) // this is bound
      }
    
      anotherMethod = () => {
        this.whateverMethodYouWant() // this is bound
      }
    }
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

为什么我的函数的es6版本说“无法读取未定义的属性'forEach'”

来自分类Dev

babel编译es6类,函数未定义

来自分类Dev

在Babel编译的方法中未定义

来自分类Dev

保存“停止”模型的实例时使用的未定义方法

来自分类Dev

为什么实例的属性未定义?

来自分类Dev

为什么变量在方法中未定义但在Typescript的构造函数中未定义

来自分类Dev

ES6类中的javascript'this'返回未定义

来自分类Dev

ES6类中的javascript'this'返回未定义

来自分类Dev

未使用Node + ES6 + Babel定义的类方法

来自分类Dev

为什么我的方法未定义?

来自分类Dev

为什么未定义我的方法?

来自分类Dev

为什么我的方法在类中未定义?(初学者)

来自分类Dev

为什么此代码中的finallyDecrypt方法未定义?

来自分类Dev

es6类组件中我的函数内部未定义props

来自分类Dev

为什么在ES6模块中导出的对象具有未定义的方法?

来自分类Dev

使用ActiveModel的Rails模型中的未定义类方法

来自分类Dev

为什么在Javascript ES6中未定义“ i”?

来自分类Dev

Rails,类中未定义的方法,但是存在方法

来自分类Dev

使用定义的实例变量运行2个方法,但仍提出未定义的局部变量

来自分类Dev

实例化python类但未定义__init __()方法时会发生什么情况?

来自分类Dev

为什么我的代码说我的对象未定义?

来自分类Dev

Rspec测试中nil类的未定义方法

来自分类Dev

在PHP中捕获未定义的类方法

来自分类Dev

对纯抽象类中的方法的未定义引用

来自分类Dev

NameError:类__init __()方法中的名称未定义错误

来自分类Dev

Rails 中类的未定义方法`build_for`

来自分类Dev

类声明中未定义超级方法

来自分类Dev

无法读取未定义的属性 - 类中的方法调用

来自分类Dev

this.props 在类方法中未定义

Related 相关文章

  1. 1

    为什么我的函数的es6版本说“无法读取未定义的属性'forEach'”

  2. 2

    babel编译es6类,函数未定义

  3. 3

    在Babel编译的方法中未定义

  4. 4

    保存“停止”模型的实例时使用的未定义方法

  5. 5

    为什么实例的属性未定义?

  6. 6

    为什么变量在方法中未定义但在Typescript的构造函数中未定义

  7. 7

    ES6类中的javascript'this'返回未定义

  8. 8

    ES6类中的javascript'this'返回未定义

  9. 9

    未使用Node + ES6 + Babel定义的类方法

  10. 10

    为什么我的方法未定义?

  11. 11

    为什么未定义我的方法?

  12. 12

    为什么我的方法在类中未定义?(初学者)

  13. 13

    为什么此代码中的finallyDecrypt方法未定义?

  14. 14

    es6类组件中我的函数内部未定义props

  15. 15

    为什么在ES6模块中导出的对象具有未定义的方法?

  16. 16

    使用ActiveModel的Rails模型中的未定义类方法

  17. 17

    为什么在Javascript ES6中未定义“ i”?

  18. 18

    Rails,类中未定义的方法,但是存在方法

  19. 19

    使用定义的实例变量运行2个方法,但仍提出未定义的局部变量

  20. 20

    实例化python类但未定义__init __()方法时会发生什么情况?

  21. 21

    为什么我的代码说我的对象未定义?

  22. 22

    Rspec测试中nil类的未定义方法

  23. 23

    在PHP中捕获未定义的类方法

  24. 24

    对纯抽象类中的方法的未定义引用

  25. 25

    NameError:类__init __()方法中的名称未定义错误

  26. 26

    Rails 中类的未定义方法`build_for`

  27. 27

    类声明中未定义超级方法

  28. 28

    无法读取未定义的属性 - 类中的方法调用

  29. 29

    this.props 在类方法中未定义

热门标签

归档