为什么instanceof对某些文字返回false?

时间:2008-10-15 04:44:21

标签: javascript literals instanceof

"foo" instanceof String //=> false
"foo" instanceof Object //=> false
true instanceof Boolean //=> false
true instanceof Object //=> false
false instanceof Boolean //=> false
false instanceof Object //=> false

// the tests against Object really don't make sense

数组文字和对象文字匹配......

[0,1] instanceof Array //=> true
{0:1} instanceof Object //=> true

为什么不是全部?或者,他们为什么不? 那么,它们是什么样的实例呢?

在FF3,IE7,Opera和Chrome中也是如此。所以,至少它是一致的。


错过了一些。

12.21 instanceof Number //=> false
/foo/ instanceof RegExp //=> true

11 个答案:

答案 0 :(得分:370)

基元是一种与Javascript中创建的对象不同的类型。来自Mozilla API docs

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

我找不到用代码构造原始类型的任何方法,也许这是不可能的。这可能是人们使用typeof "foo" === "string"代替instanceof的原因。

记住这样的事情的一个简单方法就是问自己“我想知道什么是理智和易学”?无论答案是什么,Javascript都会做另一件事。

答案 1 :(得分:90)

我用:

function isString(s) {
    return typeof(s) === 'string' || s instanceof String;
}

因为在JavaScript中字符串可以是文字或对象。

答案 2 :(得分:54)

在JavaScript中,一切都是一个对象(或者至少可以被视为一个对象),除了primitives(布尔值,空值,数字,字符串和值undefined(以及ES6中的符号)) :

console.log(typeof true);           // boolean
console.log(typeof 0);              // number
console.log(typeof "");             // string
console.log(typeof undefined);      // undefined
console.log(typeof null);           // object
console.log(typeof []);             // object
console.log(typeof {});             // object
console.log(typeof function () {}); // function

正如您所见,对象,数组和值null都被视为对象(null是对不存在的对象的引用)。区分函数是因为它们是一种特殊类型的可调用对象。但它们仍然是物体。

另一方面,文字true0""undefined不是对象。它们是JavaScript中的原始值。但是,布尔值,数字和字符串也分别具有构造函数BooleanNumberString,它们包含各自的基元以提供附加功能:

console.log(typeof new Boolean(true)); // object
console.log(typeof new Number(0));     // object
console.log(typeof new String(""));    // object

正如您所看到的,当原始值分别包含在BooleanNumberString构造函数中时,它们将成为对象。 instanceof运算符仅适用于对象(这就是原始值返回false的原因):

console.log(true instanceof Boolean);              // false
console.log(0 instanceof Number);                  // false
console.log("" instanceof String);                 // false
console.log(new Boolean(true) instanceof Boolean); // true
console.log(new Number(0) instanceof Number);      // true
console.log(new String("") instanceof String);     // true

正如您所看到的,typeofinstanceof都不足以测试值是否为布尔值,数字或字符串 - typeof仅适用于原始布尔值,数字和字符串;并且instanceof不适用于原始布尔值,数字和字符串。

幸运的是,这个问题的解决方案很简单。 toString的默认实现(即它在Object.prototype.toString上本地定义)返回原始值和对象的内部[[Class]]属性:

function classOf(value) {
    return Object.prototype.toString.call(value);
}

console.log(classOf(true));              // [object Boolean]
console.log(classOf(0));                 // [object Number]
console.log(classOf(""));                // [object String]
console.log(classOf(new Boolean(true))); // [object Boolean]
console.log(classOf(new Number(0)));     // [object Number]
console.log(classOf(new String("")));    // [object String]

值的内部[[Class]]属性比typeof值更有用。我们可以使用Object.prototype.toString创建我们自己的(更有用的)typeof运算符版本,如下所示:

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1);
}

console.log(typeOf(true));              // Boolean
console.log(typeOf(0));                 // Number
console.log(typeOf(""));                // String
console.log(typeOf(new Boolean(true))); // Boolean
console.log(typeOf(new Number(0)));     // Number
console.log(typeOf(new String("")));    // String

希望这篇文章有所帮助。要了解有关基元和包装对象之间差异的更多信息,请阅读以下博文:The Secret Life of JavaScript Primitives

答案 3 :(得分:31)

您可以使用构造函数属性:

'foo'.constructor == String // returns true
true.constructor == Boolean // returns true

答案 4 :(得分:6)

 typeof(text) === 'string' || text instanceof String; 

你可以使用它,它将适用于两种情况

  1. var text="foo"; // typeof将起作用

  2. String text= new String("foo"); // instanceof将起作用

答案 5 :(得分:1)

我相信我已经提出了一个可行的解决方案:

Object.getPrototypeOf('test') === String.prototype    //true
Object.getPrototypeOf(1) === String.prototype         //false

答案 6 :(得分:0)

这在ECMAScript规范Section 7.3.19 Step 3中定义:If Type(O) is not Object, return false.

换句话说,如果Obj中的Obj instanceof Callable不是对象,则instanceof将直接短路到false

答案 7 :(得分:0)

原始包装器类型是引用类型,每当字符串、数字或布尔值出现时,它们都会在幕后自动创建 已阅读。例如:

var name = "foo";
var firstChar = name.charAt(0);
console.log(firstChar);

这就是幕后发生的事情:

// what the JavaScript engine does
var name = "foo";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);

因为第二行使用了一个像对象一样的字符串(一个原语), JavaScript 引擎创建一个 String 实例,以便 charAt(0) 将 work.String 对象在销毁前只存在一个语句 检查this

instanceof 运算符返回 false,因为临时对象是 仅在读取值时创建。因为 instanceof 实际上并没有读取 任何东西,都没有创建临时对象,它告诉我们值不是 原始包装器类型的实例。您可以创建原始包装器 手动输入

答案 8 :(得分:-1)

https://www.npmjs.com/package/typeof

返回instanceof(构造函数名称)

的字符串表示形式
function instanceOf(object) {
  var type = typeof object

  if (type === 'undefined') {
    return 'undefined'
  }

  if (object) {
    type = object.constructor.name
  } else if (type === 'object') {
    type = Object.prototype.toString.call(object).slice(8, -1)
  }

  return type.toLowerCase()
}

instanceOf(false)                  // "boolean"
instanceOf(new Promise(() => {}))  // "promise"
instanceOf(null)                   // "null"
instanceOf(undefined)              // "undefined"
instanceOf(1)                      // "number"
instanceOf(() => {})               // "function"
instanceOf([])                     // "array"

答案 9 :(得分:-2)

对我来说是由

引起的混乱
"str".__proto__ // #1
=> String

因此"str" istanceof String应返回true,因为如何使用以下方式:

"str".__proto__ == String.prototype // #2
=> true

表达式#1 #2 的结果相互冲突,因此应该有一个错误。

#1错误

我发现它由__proto__引起的是非标准属性,因此请使用标准属性:Object.getPrototypeOf

Object.getPrototypeOf("str") // #3
=> TypeError: Object.getPrototypeOf called on non-object

现在表达#2 #3

之间没有混淆

答案 10 :(得分:-8)

或者您可以像这样制作自己的功能:

function isInstanceOf(obj, clazz){
  return (obj instanceof eval("("+clazz+")")) || (typeof obj == clazz.toLowerCase());
};

用法:

isInstanceOf('','String');
isInstanceOf(new String(), 'String');

这些都应该返回true。

相关问题