Object.create () and toString ()

Given this code

var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; }; Person.prototype = { toString: function() { return this.firstName + ' ' + this.lastName; } }; var test4 = Object.create(Person); test4.firstName = "Phat4"; test4.lastName = "Wang4"; console.log(test4.toString === Object.toString); // true console.log(test4.toString === Function.toString); // true var test5 = { firstName: "Phat5", lastName: "Wang5" }; console.log(test5.toString === test4.toString); // false console.log(test4.toString === Function.toString); // true console.log(test5.toString === Object.prototype.toString); // true console.log(test5.toString()); // [object Object] console.log(test4.toString()); // Function.prototype.toString called on incompatible object 

Why is the last line of console.log(test4.toString()) causing an error? It shows that test4.toString not like test5.toString , but I do not understand it.

Ps. I tried to search for topics and can not answer myself. Sorry if this is duplicated with anyone.

+4
source share
3 answers

Instead of this:

 var test4 = Object.create(Person); 

You must do:

 var test4 = Object.create(Person.prototype); 

The way you did this, test4 had a Person function in its prototype chain, and not an alleged prototype object that has a toString method.

Because of this, he used the toString() method, which apparently expects it to be called against the Function object.

+3
source

There is a difference between assigning a prototype and assigning a new property to a prototype object.

You declared the Person function as a constructor function, but then you pretty much assign something to your prototype by doing this:

 Person.prototype = { toString: function() { return this.firstName + ' ' + this.lastName; } }; 

This means that you assign a new variable to the toString-function object class in Person.prototype instead of actually adding a new property to it, in which you would have to do it like this:

 Person.prototype.toString = function() { return this.firstName + ' ' + this.lastName; } 

Which entails that when you actually create a new object that inherits the Person object by calling Object.create , what happens in its implementation, the new object will just be created, and then it will return this new object. which will override the prototype property that you are supposed to have created javascript by doing this Person.prototype assignment earlier in your code.

0
source
 var Person = function(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; }; var p1=new Person("Phat1","Wang1"); 

p1 - ​​object

 var p2= Object.create(Person); p2.firstName="Phat2"; p2.lastName="Wang2"; 

p2 - function

0
source

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


All Articles