问题
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!
回答1:
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();
来源:https://stackoverflow.com/questions/50074294/object-create-vs-new-in-terms-of-prototype-inheritance