javascript - 为什么我的 instanceof 运算符不响应 true?

标签 javascript ecmascript-6 ecmascript-5 ecmascript-2017

我正在尝试 instanceof 运算符。我尝试过类似的事情。

function f(){ return f; }
new f() instanceof f;
// false

为什么结果是,而这些是

function f(){ return f; }
new f() instanceof Function; 
// true

function f(){ return f; }
new f() instanceof Object;
//true

当尝试将其保存到变量时结果仍然相同

function f(){ return f; }
var n = new f();

n instanceof f;
// false

n();
// function f()

n() instanceof f;
// false

n instanceof Function     // true
n() instanceof Function   // true

为什么return f;语句改变了一切? return f 做了什么导致了这种行为?

最佳答案

首先,我建议您查看有关新运算符的文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

具体来说,请注意

When the code new Foo(...) is executed, the following things happen:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

通过显式返回f,您将覆盖正常的创建过程。当您使用 instanceof 时,您是在问“Is n 和 f 的实例”。它不是。它 f。它不是其自身的实例。

由于显然 f 是一个函数,并且 n === f,因此当您尝试确定它们是否是函数时,两者都会返回 true。此外,在 Javascript 中,函数本身就是对象(数组也是),这就是为什么 new f() instanceof Object 为 true。

关于javascript - 为什么我的 instanceof 运算符不响应 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52132128/

相关文章:

javascript - 创建用于脚本调用的切换按钮

javascript - 是否可以只检测 onkeyup 和 onpaste 之间的一个事件?

javascript - 为什么 instanceof 对 babel-node 下的 Error 子类实例不起作用?

javascript - 了解实现自定义迭代器

javascript - 如何将新项目推送到现有数组,该数组的值将从前一项中减去 10,直到它接近 0 或 0?

javascript - 使用构造函数帮助填充 Raphael 和 joint.js 功能

javascript - 无法使用sequelize和mysql根据包含的模型属性过滤数据

javascript - es6 类 - 将 boolean 值传递给构造函数

javascript - ES5 定义不可更改的数组/属性值

javascript - 如何编写一个函数,以字符串形式接收电话号码并验证它是否是美国电话号码?