![](/img/trans.png)
[英]How to allow my Product1 users to bookmark my Product2 link from Product1 web page?
[英]Javascript why Product2 is never called contrary to Product1
我正在尝试将javascript函数作为对象和异步。 为什么下面的 Product2 永远不会被调用?
function Product(title) { this.title = title; this.getInfo = function() { return this.title; } return this; } async function Product2(title) { this.title = title; this.getInfo = function() { return this.title; } console.log(this.title) return this; } async function main() { console.log("start") var product = new Product("car"); console.log(product.getInfo()); var product2 = await new Product2("car 2"); console.log(product2.getInfo()); console.log("end") } main();
并非每个函数都是构造函数。 ECMAScript 规范中的一些引用阐明了这一点:
函数对象是支持
[[Call]]
内部方法的对象。 构造函数是支持[[Construct]]
内部方法的对象。 [...] 函数对象不一定是构造函数,并且此类非构造函数对象没有[[Construct]]
内部方法。
异步函数是属于非构造函数类别的函数:
注意:类型为
async
的函数是不可构造的,并且没有[[Construct]]
内部方法或"prototype"
属性。
和:
AsyncFunction 实例不是构造函数,也没有
[[Construct]]
内部方法。 AsyncFunction 实例没有prototype
属性,因为它们不可构造。
其他不能作为构造函数的函数示例:
使用
Function.prototype.bind
或通过计算MethodDefinition (不是GeneratorMethod或AsyncGeneratorMethod )或ArrowFunction创建的函数对象没有"prototype"
属性。
由于上述原因,您的示例代码实际上遇到了异常:
Uncaught (in promise) TypeError: Product2 is not a constructor
(由于某种原因,此异常未记录在 Stack Snippet 中,但浏览器会在其控制台中显示它)
async function Product2(title)
由于这是异步的,因此执行此操作时应该有一个未捕获的 TypeError:
var product2 = await new Product2("car 2");
因为Product2
不再是构造函数。
标有 async 的函数将返回一个 Promise。
另一方面,构造函数返回它正在构造的对象。 因此,我们遇到了一种情况,您希望同时返回一个对象和一个承诺:一种不可能的情况。
new Product2将创建product2对象的实例
您不能同时使用 await 和 new 关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.