为什么下面两行返回不同的结果?
("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:
- If V is not an object, return false.
- ....
换句话说:如果 instanceof
的左侧不是对象,则运算符将返回 false。
("test".constructor == String) === true
出于不同的原因起作用:如果您尝试访问原语的属性,原语将暂时转换为对象.所以 "test".constructor
大致等于:
(new String("test")).constructor
在这种情况下,您实际上是在创建一个具有构造函数的对象,然后请求 constructor
属性。所以毫不奇怪,它将返回 String
。
关于javascript - 使用 instanceof 和检查构造函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18055980/