Node.js异步函数原型链错误 [英] Nodejs async function prototype chain error

查看:63
本文介绍了Node.js异步函数原型链错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译此代码

var Person =  function() {
console.log("CALLED PERSON")};

Person.prototype.saySomething = function() {
console.log("saySomething PERSON")};

var ape = new Person();
ape.saySomething();

此代码引发错误无法设置未定义的属性'saySomething'

and this code throws error Cannot set property 'saySomething' of undefined

var Person =  async function() {
console.log("CALLED PERSON")};

Person.prototype.saySomething = function() {
console.log("saySomething PERSON")};

var ape = new Person();
ape.saySomething();

推荐答案

当您使用 async function(){} 时,您将声明一个异步函数对象.这与常规的 function 对象不同.异步函数对象没有原型.

When you use async function() {}, you are declaring an asynchronous function object. That's different than a regular function object. The asynchronous function object does not have a prototype.

因此,当您尝试执行此操作时:

So, when you try to do this:

var Person =  async function() {
  console.log("CALLED PERSON")
};

Person.prototype.saySomething = function() {
  console.log("saySomething PERSON")
};

Person.prototype undefined ,因为在异步函数对象上没有 prototype .因此,尝试为 Person.prototype.saySomething 分配某些内容会导致您看到错误,因为 Person.prototype undefined .

Person.prototype is undefined because there is no prototype on an asynchronous function object. Thus attempting to assign something to Person.prototype.saySomething causes the error you see because Person.prototype is undefined.

这有一些逻辑,因为异步函数不能总是用作构造函数,因为异步函数总是返回一个promise,所以它永远不能像 let obj = new f().因此,拥有 .prototype 属性是没有目的的,因为它不能以这种方式使用.

There is some logic to this because an asynchronous function can't be used as a constructor because an asynchronous function always returns a promise so it can't ever return a new object as in let obj = new f(). So, there's no purpose in having a .prototype property because it can't be used that way.

如果您确实想异步创建对象,则始终可以创建一个 async 工厂函数,该函数返回一个可以通过对象解析的promise.

If you really wanted to asynchronously create an object, you could always create an async factory function that returns a promise that resolves with an object.

这篇关于Node.js异步函数原型链错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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