Function.prototype.toMethod()做什么? [英] What does Function.prototype.toMethod() do?
问题描述
我注意到实验JavaScript中的 Function.prototype
有一个 toMethod()
方法,但是其实呢如何使用它?
I noticed that the Function.prototype
has a toMethod()
method in experimental JavaScript, but what does that actually do? And how do I use it?
推荐答案
更新: toMethod
方法只是实验性的,没有达到标准。 home对象基本上是静态的,操纵 super
的唯一方法是更改[[prototype]]:
Update: the toMethod
method was experimental only and did not make it into the standard. The home object is essentially static now, the only way to manipulate super
is to change the [[prototype]]:
var base = {…}; // as below
var obj = Object.setPrototypeOf({
foo() { // needs to use method definition syntax
super.foo();
}
}, base);
obj.foo();
非常类似于 bind
函数对象的方法。然而,它不是用绑定的这个
值创建一个新的函数,而是创建一个新的函数,绑定了一个 [[HomeObject]]
,这是使用的参考对于超级
调用:
It's very similar to the bind
method of function objects. However, instead of creating a new function with a bound this
value, it creates a new function with a bound [[HomeObject]]
, which is the reference that is used for super
calls:
[[HomeObject]]
(Object):如果函数使用super
,则这是[[GetPrototypeOf]]
提供超级属性查找开始的对象。
[[HomeObject]]
(Object): If the function usessuper
, this is the object whose[[GetPrototypeOf]]
provides the object where super property lookups begin.
考虑这个例子(不使用任何类语法):
Consider this example (not using any class syntax):
var base = {
foo: function() {
console.log("base foo called on", this);
}
};
base.foo(); // base foo called on base
var obj = Object.create(base);
obj.foo(); // base foo called on obj
obj.foo = function() {
super.foo();
};
obj.foo(); // ReferenceError: this method has no home
obj.bar = obj.foo.toMethod(obj);
obj.bar(); // base foo called on obj
obj.baz = function() {
super();
};
obj.baz(); // ReferenceError: this constructor has no parent class
Reflect.setPrototypeOf(obj.baz, base.foo);
obj.baz(); // base foo called on obj
这篇关于Function.prototype.toMethod()做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!