JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – 为什么布尔基元不会调用原型toString()?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有这个代码:
Boolean.prototype.toString=function toString(){
  return this?'1':'0';
};

var object = {
  'true':'true','false':'false','1':'1','0':'0'
};

// "true" - this doesn't work
console.log('primitive',object[true]);
// "1" - but these do
console.log('primitive.toString()',object[true.toString()]);
console.log('instance',object[new Boolean(true)]);

为什么原语不使用类的toString定义?对象键是字符串或符号,它们不能只是原始的布尔值.这就是为什么我很困惑.

解决方法

因为规格这样说.
http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tostring
在这个表中,定义了基元的String值.仅使用对象 ToPrimitive.

该表告诉我们,ToString对象o是ToString(ToPrimitive(o,“String”))

规范告诉我们,如果使用Object调用ToPrimitive,我们必须遵循以下步骤:

1. If PreferredType was not passed,let hint be "default".
2. Else if PreferredType is hint String,let hint be "String".
3. Else PreferredType is hint number,let hint be "number".
4. Let exoticToPrim be GetMethod(input,@@toPrimitivE).
5. ReturnIfAbrupt(exoticToPrim).
6. If exoticToPrim is not undefined,then
  a. Let result be Call(exoticToPrim,input,«hint»).
  b. ReturnIfAbrupt(result).
  c. If Type(result) is not Object,return result.
  d. Throw a TypeError exception.
7. If hint is "default",let hint be "number".
8. Return OrdinaryToPrimitive(input,hint).

@@ toPrimitive beeing set是一个特殊情况,所以我们现在必须看看OrdinaryToPrimitive

1. Assert: Type(O) is Object
2. Assert: Type(hint) is String and its value is either "String" or "number".
3. If hint is "String",then
  a. Let methodNames be «"toString","valueOf"».
4. Else,a. Let methodNames be «"valueOf","toString"».
5. For each name in methodNames in List order,do
  a. Let method be Get(O,Name).
  b. ReturnIfAbrupt(method).
  c. If IsCallable(method) is true,then
    i. Let result be Call(method,O).
    ii. ReturnIfAbrupt(result).
    iii. If Type(result) is not Object,return result.
6. Throw a TypeError exception.

所以这意味着ToPrimitive(o,“String”)的返回值是o.toString()和toString(o.toString())与o.toString()相同.

大佬总结

以上是大佬教程为你收集整理的javascript – 为什么布尔基元不会调用原型toString()?全部内容,希望文章能够帮你解决javascript – 为什么布尔基元不会调用原型toString()?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。