【发布时间】:2018-01-28 01:00:58
【问题描述】:
谁能解释这种行为?
对于返回null 值的toString 是否有不同的处理方式?
let o1 = {
toString: function () {
return 1;
}
};
console.log(o1 == 1); // returns true
console.log(o1.toString() == 1); // returns true
const o2 = {
toString: function () {
return null;
}
};
console.log(o2 == null); // Why this comparison returns false?
console.log(o2.toString() == null); // returns true
祝您编码愉快,提前致谢!
【问题讨论】:
-
你没有覆盖任何类似的东西。 toString 属于原型。
-
o2 == null 返回 false,因为 o2 是一个对象,而 o2.toString() == null 为 true,因为您的函数返回 true
-
@Iwrestledabearonce。感谢您的评论。为什么是假的?
-
toString只有在需要类型强制时才会被==调用。由于两个操作数都是对象,所以不需要调用toString,它会比较引用。 -
@4castle 你能和我分享关于你所说的任何文件吗?谢谢!!
标签: javascript null comparison