How does the constructor get overwritten?

Tell us what’s happening:
i know the solution but i do not understand why does the constructor gets overwritten? i mean adding functions to class Dog should not overwrite class type! besides; how does a function have a constructor? i know that i am thinking with the conceptual mind of other programming languages but a function is a function and a class is the only thing that has a constructor so how come a class is the same as a function here!

Your code so far


function Dog(name) {
this.name = name;
}

// Only change code below this line
Dog.prototype = {
constructor: Dog;
numLegs: 4,
eat: function() {
  console.log("nom nom nom");
},
describe: function() {
  console.log("My name is " + this.name);
}
};

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.

Challenge: Remember to Set the Constructor Property when Changing the Prototype

Link to the challenge:

i know that i am thinking with the conceptual mind of other programming languages

Yep, that is the problem. JavaScript is not Java or any other language. JavaScript is JavaScript and it has its own rules and concepts.

An easy mistake is to try to understand JS through an object oriented programming lens - but JS isn’t OOP, it’s OOP-ish.

how does a function have a constructor? … a function is a function and a class is the only thing that has a constructor so how come a class is the same as a function here!

But in JS, a function is an object. Any object can have properties and methods on them. (In JS, everything that isn’t a primitive is some kind of an object.)

function myFunction() {
  console.log('Howdy from my function!');
}

myFunction.luckyNumber = 2003;

myFunction.reminder = () => console.log('Don\'t forget to buy milk!');

myFunction();
// Howdy from my function!

console.log(myFunction.luckyNumber);
// 2003

myFunction.reminder();
// Don't forget to buy milk!

Nuts, right?

So, the prototypal behavior is just built on specialized objects. And the class is just syntactic sugar for prototypal inheritance. And all that only vaguely matches what a class is in another language.

I would spend some time understanding what a class is (and prototypes) in JS and maybe look for materials that contrast them with whatever language you are used to.

1 Like