我正在尝试 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:
- A new object is created, inheriting from Foo.prototype.
- 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.
- 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/