我想知道是否有可能以某种方式将 javascript 箭头函数“绑定(bind)”到它所作用范围内的原型(prototype)实例。
基本上,我想使用箭头函数从原型(prototype)中获取实例变量。我知道这不能单独通过箭头函数来完成,但我很好奇是否可以在分配之前将此箭头函数绑定(bind)到实例范围。一些想法:
String.prototype.myFunction = (() => {
console.log(this.toString());
}).naiveBindNotionICantDescribe(String.prototype);
相当于:
String.prototype.myFunction = function() {
console.log(this.toString());
};
我很好奇,因为我想看看 javascript 箭头函数是否可以完全替代 javascript 函数,如果你足够了解它们并且很聪明地使用它们,或者如果没有关键字“function”是绝对不可能完成的事情,即使以巧妙的方式。
这是我的意思的一个例子:
/* anonymous self-contained demo scope. */
{
/**
* example #1: using function to reach into instance variable via prototype
* anonymous scope.
*/
{
String.prototype.get1 = function() {
return this.toString();
};
console.log('hello'.get1());
}
/**
* example 2: what I want to do but can't express in a way that works.
* This does not work.
* anonymous scope.
*/
{
String.prototype.get2 = () => {
return this.toString();
};
console.log('hello'.get2());
}
}
这是否可能,或者函数是否绝对有必要访问实例变量并且没有办法避免这种情况?
表观解:
- 包装器 magicBind(感谢 Thomas)
代码:
var magicBind = (callback) => function() {
return callback(this);
};
String.prototype.get = magicBind((self) => {
return self.toString();
});
console.log('hello'.get());
- 从“fat arrow”到“function”的函数转换器,(灵感来自 Thomas 的回答)
代码:
Function.prototype.magicBind2 = function() {
var self = this;
return function() {
return self(this);
}
};
String.prototype.get2 = ((self) => {
return self.toString();
}).magicBind2();
console.log('hello'.get2());
- 第一个没有明确使用“函数”的解决方案,它将“函数”构造函数称为 (() => {}).constructor 以避免使用“函数”或“函数”一词。
代码:
var regex = /\{([.|\s|\S]+)\}/m;
String.prototype.get = (() => {}).constructor(
(() => {
return this;
}).toString().match(regex)[0]
);
console.log('hello, world'.get());
到目前为止,这两种解决方案都允许埋葬“function”关键字,同时允许访问本地范围。
最佳答案
没有。词法绑定(bind) this
值是箭头函数的点。
它们不是函数声明和函数表达式的一般替代品。
关于javascript - 用箭头函数模拟javascript函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38809108/