gpt4 book ai didi

javascript - Object.create() 和 toString()

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:05:52 26 4
gpt4 key购买 nike

给定这些代码

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com