类未定义的构造函数中的新对象 [英] new object in constructor from class undefined

查看:101
本文介绍了类未定义的构造函数中的新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从构造函数中的类创建一个新对象,并且每当它运行时,我都会得到一个错误信息,即该操作在该方法中是未定义的,尽管它是在构造函数中定义的. Operate本身经过了全面的测试,并且可以在单独的上下文中很好地工作,所以这不是问题.我正在用Babel构建它,不是直接在Node 7.0.0中运行它

I'm creating a new object from a class in a constructor, and whenever it runs I get an error that operate is undefined in the method, though it is defined in the constructor. Operate itself is thoroughly tested and works great in a separate context so that's not the problem. I'm building it with Babel, not running it directly in Node 7.0.0

import Operate from "./operate"

export default class {

  constructor(Schema) {
    this.schema = Schema
    this.operate = new Operate(this.schema)
    console.log(this.operate.run) // <- Logs just fine
  }

  update(req, res) {
    console.log(this.operate.run) // <- Nada
    this.operate.run(req.body)
      .then(value => {
        res.status(200).json(value)
      })
  }

这感觉像是我遗漏了一些基本知识.我听说这不是一个很好的模式,所以请随时提出一个更好的方法.提前非常感谢.

This feels like I'm missing something fundamental. I've heard this isn't a great pattern anyway, so please feel free to suggest a better way. Thanks so much in advance.

UPDATE:这是使用更新的方式.我不怀疑这里有任何问题,因为当我从另一个模块(而不是类)将控制器作为函数导入时,它工作得很好

UPDATE: This is how update is being used. I don't suspect there's any problem here, as it has worked just fine when I had been importing controller as a function from another module, instead of a class

import {Router, } from "express"
import Controller from "../controller"
import User from "./user.model"

let controller = new Controller(User)
let router = new Router()

router.post("/", controller.update)

module.exports = router

推荐答案

对此进行更改:

router.post("/", controller.update)

对此:

router.post("/", controller.update.bind(controller))

当您传递controller.update时,它仅传递了指向该方法的指针,并且与controller对象的任何关联都将丢失.然后,当稍后调用该update方法时,与适当的对象没有任何关联,因此该方法中的this处理程序是错误的,并且您会看到错误.

When you pass controller.update it only passed a pointer to the method and any association with the controller object is lost. Then, when that update method is called later, there is no association with the appropriate object and thus the this handler in the method is wrong and you get the error you were seeing.

您可以在对象中强制绑定update方法,或者在将方法传递到其他地方时可能无法正确调用,可以使用上述结构来传递方法的绑定版本.

You either force the binding of the update method within the object or when you pass the method elsewhere that might not be called correctly, you can use the above structure to pass a bound version of the method.

您还可以通过将update方法的定义添加到构造函数中来将其永久绑定到您在构造函数中的对象:

You could also modify your definition of the update method to permanently bind it to your object in the constructor by adding this to the constructor:

this.update = this.update.bind(this);

这篇关于类未定义的构造函数中的新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆