javascript - Object.create() 和 toString()

标签 javascript inheritance object prototypal-inheritance

给定这些代码

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

为什么最后一行 console.log(test4.toString()) 抛出错误?它表明 test4.toString 不像 test5.toString 但我不明白..

附言。我已经尝试搜索线程,但仍然无法回答自己。对不起,如果这与任何重复。

最佳答案

取而代之的是:

var test4 = Object.create(Person);

你应该这样做:

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

你的方式,test4Person 函数 在其原型(prototype)链中,而不是具有您的 toString 的预期原型(prototype)对象方法。

因此,它使用了 toString()显然预期会针对 Function 调用的方法对象。

关于javascript - Object.create() 和 toString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8557110/

相关文章:

java - 在这种情况下如何避免代码重复?

iphone - 删除 NSMutablearray 中的最后一个对象

javascript - 在带空格的对象内搜索字符串名称

javascript - 如何按数组值对 javascript 对象进行排序

javascript - 垂直居中上传的图像预览

javascript - 过滤字符串中找到的所有主题标签

class - 由于开闭原则处理继承层次结构

c# - 从 cs 页面启用/禁用必填字段验证器?

javascript - jQuery - 检查是否触发了 .noconflict

android - 继承和泛型 java android