简体   繁体   中英

Can I create my own “then()” function in Javascript and execute it?

I was going through a tutorial about Promises in Javascript. I saw usages of then() method in many places.

When I wrote the below code, I saw the "then()" function under __proto__ section of the console.

const myPromise = new Promise(function(resolve, reject) {});
console.log(myPromise);

But I am not able to observe the same "then()" function when I wrote the below code,

class Car {
   constructor(color, type, doors) {
      this.color = color;
      this.type = type;
      this.doors = doors
   }
}
const myCar = new Car('blue', 'sedan', '4');
console.log(myCar);

So , I was thinking that , Can we create our own then() function in Javascript and execute it?.

It is because when you create promise it's __proto__ points to Promise.prototype and when you create a object using class it's __proto__ points to Object.prototype

for more information read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

and yes we can create our own then function and execute it but we should not do this unless you know exactly what you are doing

here is a example to create our own then method

class myObj extends Object {
  then() {
    console.log('then is called');
  }
}

var mo = new myObj()

and now you can call mo.then()

Have a look at this blog post. You should have a pretty solid idea of what promises are all about when you are finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM