使用instanceof和检查构造函数之间有什么区别? [英] What's the difference between using instanceof and checking the constructor?

查看:85
本文介绍了使用instanceof和检查构造函数之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why do the following two lines return different results?

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

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

Tested in the console of chrome version 28.0.1500.95 m

本机类型的工作方式是否略有不同?

Does it work slightly differently for native types?

推荐答案

构造函数只是内部 [[prototype]] 属性的属性,可以轻松实现操纵:

constructor is just a property of the internal [[prototype]] property, that can easily be manipulated:

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

var a = new A();

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

instanceof 运算符然而检查即使您更改了构造函数的完整 prototype 属性,内部原型链并不容易被愚弄:

The instanceof operator however checks the internal prototype chain and is not so easily to be fooled, even if you change the complete prototype property of the constructor function:

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

var a = new A();

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






那么,为什么testinstanceof String === false 但是(test.constructor == String)=== true

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

First of all, "test" is a primitive and primitives are never an instance of anything. What actually happens when you use instanceof is that the internal [[HasInstance]] method of the constructor is called with the possible instance as an argument. So a instanceof A translates roughly to:

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

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

The ECMA Specs have this to say to [[HasInstance]]: http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5.3


[[HasInstance]](V)

假设F是一个Function对象。

Assume F is a Function object.

当使用值V,
调用F的[[HasInstance]]内部方法时,将执行以下步骤:

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



  1. 如果V不是对象,则返回false。

  2. ....



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

In other words: If the left hand side of instanceof is not an object, the operator will return false.

(test.constructor == String)=== true works f或者不同的原因:如果您尝试访问基元的属性,则基元将临时转换为对象。所以test.constructor 大致等于:

("test".constructor == String) === true works for a different reason: If you try to access a property of a primitive, the primitive will be temporarily converted into an object. So "test".constructor is roughly equal to:

(new String("test")).constructor

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

in which case you are actually creating an object, with a constructor function and requesting the constructor property afterward. So it is no surprise, that it will return String.

这篇关于使用instanceof和检查构造函数之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆