In Javascript, why setting a prototype in a constructor function changes the value of .constructor to its instance?

function Human(){
  this.job = 'code'
}

//Human.prototype = {feeds: 'Pizza'};

var developer = new Human();

console.log(developer.constructor);

Above Console Logs

function Human() {
this.job = 'code';
}

When I uncomment a line Human.prototype = {feeds: 'Pizza'};, its console logs

function Object() {
  [native code]
}

Why does installing a prototype on a constructor function affect who is the constructor of the object created by the constructor?

Another example:

function LivingBeing() {
  breathes: 'air';
}

function Human(){
  feeds: 'Pizza';
}

//Human.prototype = new LivingBeing();

var developer = new Human();
console.log(developer.constructor);

With a comment, as he says, the constructor of Human, when he does not comment on it, says LivingBeing. Why does the designer go further when something is really found on the prototype?

I thought to add another level to this

function AThing(){
  this.say = function(){return 'I am thing';};
}

function LivingBeing() {
  breathes: 'air';
}

LivingBeing.prototype = new AThing();

function Human(){
  feeds: 'Pizza';
}

Human.prototype = new LivingBeing();

var developer = new Human();
console.log(developer.constructor);

Now its developer is the AThing developer. Can I say that the designer goes as far as possible in the prototype chain?

+4
source share
2 answers

developer constructor, , , . , Object().

function Human(), JS prototype constructor :

X = {}
Human.prototype = X
X.constructor = Human

, dev = new Human, __proto__ dev X, dev.constructor X.constructor, Human.

"pizza", :

Human.prototype = X
X.constructor = Human

pizza = {feeds:'Pizza'}
// pizza.__proto__ = {}
// pizza.constructor = pizza.__proto__.constructor = Object

Human.prototype = pizza
// note that pizza.constructor does NOT change

dev = new Human
// dev.__proto__ = Human.prototype = pizza

dev.constructor
// dev.constructor = dev.__proto__.constructor = pizza.constructor = pizza.__proto__.constructor = Object()
+2

?

Object, . , , , . , 1, true "".

:

developer function Human(){this.job = "code";}.

:

, Object {}.

, javascript [native code]. .

0

Source: https://habr.com/ru/post/1537077/


All Articles