Diiference between functionName.constructor and functionName.prototype.constructor

Diiference between functionName.constructor and functionName.prototype.constructor
0

#1

Tell us what’s happening:
My original code is this :-1:

Your code so far


function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };

function Dog() { }

// Add your code below this line

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function(){`Preformatted text`
    return "Bo Bo Bo";
}

// Add your code above this line

let beagle = new Dog();

beagle.constructor == Dog // return true;

Now instead of

Dog.prototype.constructor = Dog;
// If  I do this
Dog.constructor = Dog;
// Then 
beagle.constructor == Dog  // return false why?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance/


#2

@CoderOO7,

Add all necessary code so the Dog object inherits from Animal and the Dog's prototype constructor is set to Dog. Then add a bark() method to the Dog object so that beagle can both eat() and bark() . The bark() method should print “Woof!” to the console.

Your code:

Dog.prototype.bark = function(){`Preformatted text`
    return "Bo Bo Bo";
}

#3

I know about my code, I want to know the difference between Dog.constructor = Dog; AND Dog.prototype.constructor = Dog;
Try it in your browser console.


#4

The difference between the two lies in how JavaScript is build.
Every function has the prototype Function() (think of it as similar to every object inheriting from the Object class in Java). So, for instance, if you have a constructor, I.E. Dog, then you basically have class Dog extends Function.

When using Dog.prototype.constructor you are referencing the Object function that created an instance of Dog’s prototype. This references Dog.prototype and not Dog.

There is a more detailed explanation here


#5

Hi @CoderOO7,

It returns false because constructor property is only found on a function’s .prototype object.
Since you replaced .prototype object Dog.prototype = Object.create(Animal.prototype);. The .constructor property is lost. JS have object delegation as inheritance, it delegates to prototype chain and finds .constructor on the Animal's .prototype.

So

Dog.constructor = Dog;
let beagle = new Dog();

beagle.constructor == Animal; //true