Given these 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 does the last line console.log(test4.toString()) throws error ? It shows that test4.toString is not like test5.toString but I don’t get it ..
Ps. I’ve tried searching the threads and still cannot answer myself. Sorry if this duplicates with any.
Instead of this:
You should be doing:
The way you had it,
test4had thePersonfunction in its prototype chain, not the intended prototype object that has yourtoStringmethod.Because of this, it was using a
toString()method that is apparently anticipating being called against aFunctionobject.