【发布时间】:2016-08-06 22:02:43
【问题描述】:
我想知道是否有可能以某种方式将 javascript 箭头函数“绑定”到其作用域的原型实例。
基本上,我想使用箭头函数从原型中获取实例变量。我知道这不能仅通过箭头函数来完成,但我很好奇是否可以在分配它之前将此箭头函数绑定到实例范围。类似的想法:
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());
}
}
这是可能的吗,或者是函数绝对需要访问实例变量并且没有办法绕过这个?
明显的解决方案:
- wrapper magicBind(感谢 Thomas)
代码:
var magicBind = (callback) => function() {
return callback(this);
};
String.prototype.get = magicBind((self) => {
return self.toString();
});
console.log('hello'.get());
- 从“胖箭头”到“函数”的函数转换器,(受 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”关键字,同时允许访问本地范围。
【问题讨论】:
-
只有 1 个问题:为什么要用粗箭头语法版本替换每个函数?你想失去兼容性吗?
-
胖箭头没有自己的
this或arguments-object。所以你不能用胖箭头完全替换函数。海事组织。它们的主要目的是充当回调函数。 -
我想了解是否可以这样做。我正在考虑javascript是否可以在没有“function”关键字的情况下存在。是的,兼容性很糟糕,但是如果您了解它们之间的关系并且可以相互表达,您可以通过编写自己的解析器轻松地将箭头函数转换为函数(反之亦然)。
-
@Dmitry — No.
bind/apply/call/etc 对箭头函数没有影响。 -
@Dmitry 您在粗箭头内看到/使用的
this是一个闭包,您将this变量从周围的上下文中封闭起来。它与实际的(胖箭头)函数调用无关。arguments也是如此。
标签: javascript functional-programming