为什么在 JavaScript 中 Object instanceof Function 和 Function instanceof Object 都返回 true?
我在 Safari WebInspector 中试过了。
最佳答案
我花了一段时间才弄明白,但这真的值得花时间。首先,让我们看看 instanceof 是如何工作的。
引自MDN ,
The
instanceofoperator tests whether an object has in its prototype chain theprototypeproperty of a constructor.
[instanceof]现在,让我们看看如何instanceof由 ECMA 5.1 规范定义,
The production
RelationalExpression: RelationalExpression instanceof ShiftExpressionis evaluated as follows:
- Let
lrefbe the result of evaluatingRelationalExpression.- Let
lvalbeGetValue(lref).- Let
rrefbe the result of evaluatingShiftExpression.- Let
rvalbeGetValue(rref).- If
Type(rval)is not Object, throw aTypeErrorexception.- If
rvaldoes not have a[[HasInstance]]internal method, throw aTypeErrorexception.- Return the result of calling the
[[HasInstance]]internal method ofrvalwith argumentlval.
首先计算左侧和右侧表达式 (GetValue),然后右侧结果应该是一个带有 [[HasInstance]] 内部方法的对象。并非所有对象都有 [[HasInstance]] 内部方法,但有函数。例如,以下将失败
console.log(Object instanceof {});
# TypeError: Expecting a function in instanceof check, but got #<Object>
[[HasInstance]]现在,让我们看看如何[[HasInstance]]已在 ECMA 5.1 规范中定义,
Assume
Fis a Function object.When the
[[HasInstance]]internal method ofFis called with valueV, the following steps are taken:
- If
Vis not an object, returnfalse.- Let
Obe the result of calling the[[Get]]internal method ofFwith property name"prototype".- If
Type(O)is not Object, throw aTypeErrorexception.- Repeat
- Let
Vbe the value of the[[Prototype]]internal property ofV.- If
Visnull, returnfalse.- If
OandVrefer to the same object, returntrue.
就是这么简单。获取 F 的 prototype 属性并将其与 O 的 [[Prototype]] 内部属性进行比较,直到它变为 null 或 F 的 prototype 与 O 相同。
[[prototype]] 内部属性首先让我们看看什么是[[prototype]] internal property ,
All objects have an internal property called
[[Prototype]]. The value of this property is eithernullor an object and is used for implementing inheritance. Whether or not a native object can have a host object as its[[Prototype]]depends on the implementation. Every[[Prototype]]chain must have finite length (that is, starting from any object, recursively accessing the[[Prototype]]internal property must eventually lead to anullvalue).
注意:我们可以通过 Object.getPrototypeOf 获取这个内部属性功能。
原型(prototype)属性[[HasInstance]] 还讨论了另一个名为 prototype 的属性,它特定于 Function 对象。
The value of the
prototypeproperty is used to initialise the[[Prototype]]internal property of a newly created object before the Function object is invoked as a constructor for that newly created object.
这意味着,当函数对象被用作构造函数时,将创建一个新对象,并且新对象将使用此原型(prototype)初始化其内部 属性。例如,[[Prototype]]
function Test() {}
Test.prototype.print = console.log;
console.log(Object.getPrototypeOf(new Test()) === Test.prototype);
# true
现在让我们回到实际的问题。让我们来看第一种情况
console.log(Object instanceof Function);
# true
它将首先获取Function.prototype,然后尝试查找该对象是否在Object 的原型(prototype)层次结构中。让我们看看结果如何
console.log(Function.prototype);
# [Function: Empty]
console.log(Object.getPrototypeOf(Object));
# [Function: Empty]
console.log(Object.getPrototypeOf(Object) === Function.prototype);
# true
由于 Function.prototype 匹配 Object 的内部属性 [[Prototype]],它返回 true.
现在让我们来看第二种情况
console.log(Function instanceof Object);
# true
console.log(Object.prototype);
# {}
console.log(Object.getPrototypeOf(Function));
# [Function: Empty]
console.log(Object.getPrototypeOf(Function) === Object.prototype);
# false
console.log(Object.getPrototypeOf(Object.getPrototypeOf(Function)));
# {}
Object.getPrototypeOf(Object.getPrototypeOf(Function)) === Object.prototype
# true
在这里,首先我们得到 Object.prototype,即 {}。现在,它正在尝试查找 Function 的原型(prototype)链中是否存在相同的对象 {}。 Function 的直接父级是 Empty 函数。
console.log(Object.getPrototypeOf(Function));
# [Function: Empty]
它与Object.prototype不同
console.log(Object.getPrototypeOf(Function) === Object.prototype);
# false
但是 [[HasInstance]] 算法并不止于此。它重复并上升一个层次
console.log(Object.getPrototypeOf(Object.getPrototypeOf(Function)));
# {}
这与 Object.prototype 相同。这就是返回 true 的原因。
关于javascript - 为什么在 JavaScript 中 "Object instanceof Function"和 "Function instanceof Object"都返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23622695/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串