let obj = {
foo: function() {},
bar() {} // 为什么这种方式就不能使用 new 呢
}
new obj.foo(); // 正常
new obj.bar(); // 报错 obj.bar is not a constructor
// 打印 obj,foo 和 bar 没有差异
console.log(obj) // { foo: [Function: foo], bar: [Function: bar] }
// 打印 obj.foo 和 obj.bar 的 constructor, 也没有差异
console.log(obj.foo.constructor); // [Function: Function]
console.log(obj.bar.constructor); // [Function: Function]
想问下在 obj
里面,为什么使用 bar(){}
这种方式就不能使用 new
操作呢?
一个对象能不能 new 要看它有没有
[[Construct]]
槽。在创建函数的时候
[[Construct]]
槽的建立时有条件的:FunctionAllocate 只有 "normal" 函数才可以。在 FunctionCreate 调用 FunctionAllocate,做过一次类型映射,但 Normal 还是 normal
在 DefineMethod里调用 FunctionCreate ,只有
functionPrototype
存在才是 NormalObject 内的函数定义(你的第二种形式),调用 DefineMethod 没有提供
functionPrototype
PropertyDefinitionEvaluation于是,它不能构造 ....
你的第一种形式走的是另一条路,并没有通过 DefineMethod ....