使对象不可调用 [英] Making an object non-callable

查看:71
本文介绍了使对象不可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,函数是可调用的。

In JavaScript, functions are callable.

我可以从函数中删除此属性,只留下一个普通对象吗?

Can I remove this attribute from a function, leaving only a normal object?

var foo = function () {};
foo.[[callable]] = false; // pseudocode
foo(); // "foo is not a function"


推荐答案


我可以从函数中删除此属性,只留下普通对象吗?

Can I remove this attribute from a function, leaving only a normal object?

否。函数(评估行为,而不是它们的对象属性)几乎是不可变的。

No. Functions (the evaluation behaviour, not their object properties) are pretty much immutable.

callability 对象取决于它们是否有 [[call]] 插槽。 规范说明了那些


内部插槽是作为创建对象的过程的一部分分配的,可能无法动态添加到对象。

(暗示它们也无法动态删除)。此外,这些内部方法不是ECMAScript语言的一部分不是对象属性,这意味着它们不能被访问,设置,删除或操纵可以想象的方式通过语言。

(and it is implied that they cannot dynamically be removed either). Furthermore, "These internal methods are not part of the ECMAScript language" and "are no object properties", which means they cannot be accessed, set, deleted or manipulated in any imaginable way by the means of the language.

[[call]] 插槽是各种对象的一部分,其中它们总是包含一个内部方法,但除了初始化(一次)外,它们永远不会发生变异。它们有各种各样的类型:

[[call]] slots are part of various objects, where they always contain an internal method, but they are never mutated except for their initialisation (once). They come in various kinds:

  • [[call]] of user-defined function objects, initialised in step 8 of FunctionAllocate
  • [[call]] of builtin function objects, initialised implicitly by the environment
  • [[call]] of bound function objects, initialised in step 6 of BoundFunctionCreate
  • [[call]] of some proxy objects, initialised conditionally in step 7a of ProxyCreate iff the proxy target is callable as well

正如您所看到的,没有办法改变甚至删除对象的 [[call]] 槽,甚至在代理上也是如此。你最好的选择是

As you can see, there is no way to alter or even remove the [[call]] slot of an object, not even on proxies. Your best bet is


  • 在不合时宜状态下调用函数抛出 / li>
  • 通过

  • make the function throw when called in an inopportune state
  • create a new, uncallable object from the function by means of

var obj = Object.assign(Object.create(Object.getPrototypeOf(fn)), fn);


这篇关于使对象不可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆