javascript - 使用 instanceof 和检查构造函数有什么区别?

标签 javascript

为什么下面两行返回不同的结果?

("test" instanceof String) // returns false
("test".constructor == String) // returns true

在chrome版本28.0.1500.95m的控制台测试

对于原生类型,它的工作方式是否略有不同?

最佳答案

constructor 只是内部 [[prototype]] 属性的一个属性,可以轻松操作:

function A(){}
function B(){}
A.prototype.constructor = B;

var a = new A();

console.log(a.constructor); //B

不过,instanceof 运算符会检查内部原型(prototype)链,并且不会那么容易被愚弄,即使您更改构造函数的完整 prototype 属性也是如此:

function A(){}
function B(){}
A.prototype = B.prototype;

var a = new A();

console.log(a instanceof A); //true
console.log(a instanceof B); //false

那么,为什么 "test"instanceof String === false("test".constructor == String) === true

首先,“test” 是一个原语,而原语从来不是任何事物的实例。当您使用 instanceof 时实际发生的是构造函数的内部 [[HasInstance]] 方法以可能的实例作为参数被调用。所以 a instanceof A 大致翻译为:

`A.[[HasInstance]](a)`

ECMA 规范对 [[HasInstance]] 说:http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5.3

[[HasInstance]] (V)

Assume F is a Function object.

When the [[HasInstance]] internal method of F is called with value V, the following steps are taken:

  1. If V is not an object, return false.
  2. ....

换句话说:如果 instanceof 的左侧不是对象,则运算符将返回 false。

("test".constructor == String) === true 出于不同的原因起作用:如果您尝试访问原语的属性,原语将暂时转换为对象.所以 "test".constructor 大致等于:

(new String("test")).constructor

在这种情况下,您实际上是在创建一个具有构造函数的对象,然后请求 constructor 属性。所以毫不奇怪,它将返回 String

关于javascript - 使用 instanceof 和检查构造函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18055980/

相关文章:

javascript - 如何在Javascript中按值查找键?

javascript - webpack 是编译时间很慢

javascript - 如何在页面中央放置一个div和frame

javascript - 1 个或多个整数后跟非整数的正则表达式

javascript - 如何将 javascript 函数延迟到 Jquery 和 Facebook 都加载之后?

javascript - 如何将客户端 .STL 文件加载到 Three.js 场景中而不是从服务器加载?

javascript - Adobe PDF Forms Javascript,不同字段的求和值

javascript - 根据位置隐藏/显示图标。搜索?

javascript - 如何在鼠标位置打开jquery工具提示并将其保留在那里

javascript - Kendo MVC Chart - 渲染事件问题