Object 定义的方法,为什么不能使用 new 实例化呢

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 操作呢?

阅读 2.1k
1 个回答

一个对象能不能 new 要看它有没有 [[Construct]] 槽。

在创建函数的时候 [[Construct]] 槽的建立时有条件的:FunctionAllocate 只有 "normal" 函数才可以。

FunctionCreate 调用 FunctionAllocate,做过一次类型映射,但 Normal 还是 normal

DefineMethod里调用 FunctionCreate ,只有 functionPrototype 存在才是 Normal

Object 内的函数定义(你的第二种形式),调用 DefineMethod 没有提供 functionPrototype PropertyDefinitionEvaluation

于是,它不能构造 ....

你的第一种形式走的是另一条路,并没有通过 DefineMethod ....

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题