Node.js异步函数原型链错误

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.