-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
let err = new TypeError()
err instanceof TypeError // true (fine...
err instanceof Error // true (fine...
Error() instanceof TypeError // false (fine...
Error() instanceof Error // true (wtf???
Object() instanceof Object // true
Promise.resolve() instanceof Promise // true
Question:
Error() 为何会是 Error的instance?不加new应该是普通的函数调用啊,为何会是实例呢?不科学啊,难道内置的构造函数有什么魔力?
Answer:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
a instanceof A
-> A.prototype
是否出现在a的原型链上 -> a.__proto__
是否指向A.prototype
- 创建一个崭新的对象
- 确定对象的原型继承关系,对象的__proto__属性(可读不可写)指向构造函数的
prototype
属性(可读可写)即:a.__proto__ = A.prototype
- 上下文环境
this
指向刚创建的那个崭新的对象 - 执行构造函数。
- 如果构造函数有明确返回值(通常不会有),则这个返回值成为整个new表达式的结果,否则那个崭新的对象成为new表达式的结果
恍然大雾:原来继承是通过对象的引用实现,然后控制只有上游可写,下游只能读。
所以:
function Foo(){}
new Foo() 等价于 new Foo
所以: Error() instanceof Error
的一种合理解释:
function Error() {
return Object.create(Error)
}
关于Error: 除了Error还有其他7种内置的错误构造函数: EvalError
、InternalError
、RangeError
、ReferenceError
、SyntaxError
、URIError
、TypeError
Metadata
Metadata
Assignees
Labels
No labels