【问题标题】:JS: When is Function.prototype.apply() or call() necessary to refer to thisJS:Function.prototype.apply() 或 call() 什么时候需要引用 this
【发布时间】:2021-10-10 01:30:49
【问题描述】:

我正在学习 JS。我正在使用 Mongoose,我想将函数和参数传递给回调,但我必须改用 call()。

// Car is a model. Using Express in Node.js
express.Router().route('/')
    .get((req,res,next)=>{
        print(res,next,Cars.find)
    })

const print = async(res,next,func,param1={})=>{
    try {
        const cars = await func.call(Cars,param1)
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(cars);
    } catch (err)
        next(err);
}

当我在 print(...) 中简单地执行 func(param1) 时,它对我不起作用,它会返回此错误。

MongooseError: `Model.find()` cannot run without a model as `this`.
Make sure you are calling `MyModel.find()` where `MyModel` is a Mongoose model.

您能否解释一下为什么会这样以及何时需要使用 apply()/call() 来传递它?在猫鼬的这种情况下和一般情况下?

我对 next() 和 next(err) 也有点困惑。文档说这只是为了让程序可以在某种意义上“跳过”错误,我可以明显地看到这一点。但它是像我们可以修改的回调函数还是内置的?

编辑:我在看How to access the correct `this` inside a callback,是不是因为不知何故该对象没有传递到print()

【问题讨论】:

  • 那行不通。 func_param1 = {} 不可迭代
  • @CertainPerformance 哦,我看到我在开发代码中使用了 call() 而不是 apply()。但是 apply() 或 call() 的语法不是我要问的。我将其更改为 call()。谢谢。
  • 您不应该在这里使用call - 现在您的print 函数仅适用于Cars 模型。相反,使用简单的await func();,但将Cars.find.bind(Cars, {})() => Cars.find({}) 作为回调传递。
  • 感谢@Bergi。因为对于不同的http请求我会使用不同的方法,所以我会在父函数get()中调用Cars.find()。这种方式更容易调试。但这绝对是我工具箱中的一个工具。

标签: javascript this apply pass-by-reference next


【解决方案1】:

在 js 中,thisis determined at run time 指的是运行该方法的对象。如果方法由箭头函数定义或在箭头函数中调用,则this 会冒泡到父函数。在这种情况下,如果我没有使用 call()this 将是 get()。所以我在某种意义上是正确的,父对象Cars 没有与Cars.find() 一起传递。

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2012-06-05
    • 2014-05-06
    • 2013-10-22
    • 2018-12-10
    相关资源
    最近更新 更多