简体   繁体   中英

Object.create vs new in terms of prototype inheritance

I have searched a lot about it but I couldn't find any direct answer to it

Why we can't access prototype property/method of an object created using Object.create() but we can using new keyword?

Let us consider a constructor function Greeting as follows:

function Greeting() {   
}
Greeting.prototype.byeBye = function(){
    console.log("Have a good day!")
}

Now I create an object from this constructor using Object.create() method

var Stanley = Object.create(Greeting)
console.log(Stanley.byeBye())

Output -  Error: Stanley.byeBye is not a function

Which means byeBye() function cannot be accessed directly using Stanley object

If you check for Stanley object in console, then you will find the following structure:

在此处输入图片说明

However if we use the new keyword to create the object, then we can access byeBye() prototype function directly

var Hamley = new Greeting()
console.log(Hamley.byeBye())

Output: Have a good day!

On checking the structure of Hamley object in console, we get it like this:

在此处输入图片说明

My doubt is that why we can't access prototype property/method of an object created using Object.create() but we can using the new keyword.

Another doubt is that why in case of Object.create() , prototype method byeBye() comes under seperate property in __proto__ called as ' prototype '. Whereas in case of new , byeBye() function is directly available under __proto__ .

Note: Please check the links to open the images related to second doubt

Thanks to anyone who answers to this post!

The object you give to Object.create should be the prototype you want the new object to have. You're passing in the constructor function, so that's making the constructor function the prototype of the object. You probably meant to use the same object new would use, which is on the prototype property of the constructor.

So instead of:

var Stanley = Object.create(Greeting)

you want

var Stanley = Object.create(Greeting.prototype)
// ---------------------------------^^^^^^^^^^

Live Example:

 function Greeting() { } Greeting.prototype.byeBye = function(){ console.log("Have a good day!"); } var Stanley = Object.create(Greeting.prototype); Stanley.byeBye(); 

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