没有toString方法

No toString method

本文关键字:方法 toString 没有      更新时间:2023-09-26

我正在学习JavaScript,我在代码库中发现if语句的哪一部分是多余的。

if(undefined === value || null === value || !value.toString)

是否有一些在js没有toString定义(除了undefinednull)?

如果该代码的目的是检查value变量是否定义了toString方法,那么它是奇怪的,因为唯一会计算为false的情况是value未定义。

我冒昧地用以下代码为您创建了一个小提琴(http://jsfiddle.net/gnrcc/2/):

var obj = new String("Hi, im an object"); // String object
var str = "Hello, im a primitive" // string primitive
var und; // undefined
// will output native method, string and object details
console.log(obj.toString, obj.toString(), obj); 
// will output native method, string and string
console.log(str.toString, str.toString(), str);  
// will get property undefined error
console.log(und.toString, und.toString(), und); 
  • 所有对象都有toString方法(来自对象原型)
  • 当一个方法被调用时,所有的原语将被它们相应的对象自动包装,导致与对象相同的行为(编辑:异常显然是未定义的原语)