Reputation: 627
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?.
Upvotes: 0
Views: 785
Reputation: 3558
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()
Upvotes: 1