Why is it necessary to set the prototype constructor?

前端 未结 14 1759
孤城傲影
孤城傲影 2020-11-22 02:54

In the section about inheritance in the MDN article Introduction to Object Oriented Javascript, I noticed they set the prototype.constructor:

// correct the          


        
14条回答
  •  心在旅途
    2020-11-22 03:09

    Here's one example from MDN which I found very helpful to understand its uses.

    In JavaScript, we have async functions which returns AsyncFunction object. AsyncFunction is not a global object but one may retrieve it by using constructor property and utilize it.

    function resolveAfter2Seconds(x) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(x);
        }, 2000);
      });
    }
    
    // AsyncFunction constructor
    var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
    
    var a = new AsyncFunction('a', 
                              'b', 
                              'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
    
    a(10, 20).then(v => {
      console.log(v); // prints 30 after 4 seconds
    });
    

提交回复
热议问题