Function.prototype.toMethod() 有什么作用? [英] What does Function.prototype.toMethod() do?

查看:12
本文介绍了Function.prototype.toMethod() 有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在实验性 JavaScript 中 Function.prototype 有一个 toMethod() 方法,但这实际上是做什么的?我该如何使用它?

解决方案

更新:toMethod 方法只是实验性的,并没有成为标准.home 对象现在基本上是静态的,操作 super 的唯一方法是更改​​ [[prototype]]:

var base = {…};//如下var obj = Object.setPrototypeOf({foo() {//需要使用方法定义语法超级.foo();}}, 根据);obj.foo();

<小时>

它与函数对象的bind 方法非常相似.然而,它不是创建一个带有绑定 this 值的新函数,而是创建一个带有绑定 [[HomeObject]],这是用于super调用的引用:<块引用>

[[HomeObject]] (Object):如果函数使用super,这是[[GetPrototypeOf]]提供的对象超级属性查找开始的对象.

考虑这个例子(不使用任何类语法):

var base = {富:函数(){console.log("base foo 调用", this);}};base.foo();//在 base 上调用 base foovar obj = Object.create(base);obj.foo();//基 foo 在 obj 上调用obj.foo = 函数(){超级.foo();};obj.foo();//ReferenceError: 这个方法没有homeobj.bar = obj.foo.toMethod(obj);obj.bar();//基 foo 在 obj 上调用obj.baz = 函数(){极好的();};obj.baz();//ReferenceError: 这个构造函数没有父类Reflect.setPrototypeOf(obj.baz, base.foo);obj.baz();//基 foo 在 obj 上调用

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?

解决方案

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();


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): If the function uses super, 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屋!

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