Skip to content
陈广亮的技术博客
Go back

JS 类型转换:对象转原始值

对象转换成原始值的过程:

  1. 如果对象有 valueOf() 方法并返回原始值,则调用
  2. 否则调用 toString() 方法
  3. 否则抛出类型异常
function T() {}
T.prototype.valueOf = function () {
  return "a";
};
new T() == "a"; // true

T.prototype.valueOf = function () {
  return {};
};
T.prototype.toString = function () {
  return "b";
};
new T() == "b"; // true

注意:Date 类型转换成原始值只使用 toString() 方法。


Share this post on:

Previous Post
JS 判断浏览器是否支持严格模式
Next Post
String.concat 与 apply 的妙用