function Dog(name) {
this.name = name;
}
Dog.prototype = {
constructor: Dog,
age: 16,
eat: function() {
console.log('this function works')
}
}
let beagle = new Dog("Snoopy");
console.log(Dog.prototype);
console.log(beagle.prototype);
beagle.eat();
The console outputs the prototype for the constructor function, but returns undefined for the prototype of the beagle. If I call eat() on the beagle however, it outputs 'This function works'. Why is the prototype undefined, despite the fact that I can still call the function eat() on the beagle object?
CodePudding user response:
Prototype
is the property of the constructor function, so that's why beagle
don't have beagle.prototype
as a property but all ordinary objects in JavaScript have an internal prototype slot which is not a .prototype
property but __proto__
and you can access it with .__proto__
like this:
function Dog(name) {
this.name = name;
}
Dog.prototype = {
constructor: Dog,
age: 16,
eat: function() {
console.log('this function works')
}
}
let beagle = new Dog("Snoopy");
console.log(Dog.prototype);
console.log(beagle.__proto__);
beagle.eat();