繁体   English   中英

用箭头功能模拟javascript函数

[英]simulating javascript function with arrow function

我想知道是否有可能以某种方式将javascript箭头函数“绑定”到其作用域内的原型的实例。

基本上,我想使用箭头函数从原型中获取实例变量。 我知道这不能仅通过箭头函数来完成,但是我很好奇是否有可能在分配它之前将该箭头函数绑定到实例范围。 遵循以下想法:

String.prototype.myFunction = (() => {
    console.log(this.toString());
}).naiveBindNotionICantDescribe(String.prototype);

相当于:

String.prototype.myFunction = function() {
    console.log(this.toString());
};

我很好奇,因为如果您对JavaScript箭头功能了解得足够多并且很聪明,或者如果没有关键字“ function”,即使没有聪明的话,如果没有某些事情是绝对不可能完成的,那么我想看看javascript箭头功能是否可以完全替代javascript功能方法。

这是我的意思的示例:

/* 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());  
    }  
}

这是可能做到的,还是进入实例变量绝对必要的功能,并且没有办法避免吗?

表观解决方案

  1. 包装魔术贴(感谢托马斯)

码:

var magicBind = (callback) => function() { 
    return callback(this);
};
String.prototype.get = magicBind((self) => {
    return self.toString();
});
console.log('hello'.get());
  1. 从“胖箭头”到“功能”的功能转换器(受托马斯的答案启发)

码:

Function.prototype.magicBind2 = function() {
    var self = this;

    return function() {
        return self(this);
    }
};

String.prototype.get2 = ((self) => {
    return self.toString();
}).magicBind2();

console.log('hello'.get2());
  1. 不明确使用“功能”的第一个解决方案,将“功能”构造函数称为(()=> {})。constructor,以避免使用单词“功能”或“功能”。

码:

var regex = /\{([.|\s|\S]+)\}/m;

String.prototype.get = (() => {}).constructor(
    (() => {
        return this;
    }).toString().match(regex)[0]
);

console.log('hello, world'.get());

到目前为止,这两种解决方案都允许在访问本地范围的同时埋入“功能”关键字。

否。按词法绑定this值是箭头功能的要点

它们不是函数声明和函数表达式的一般替代。

我知道这不能仅通过箭头函数来完成,但是我很好奇是否有可能在分配它之前将该箭头函数绑定到实例范围。

没错,它可以单独完成的,但你可以做this通过包装成为一个正常的函数内所需的值...:

 String.prototype.get2 = function() { return (() => this.toString())(); }; console.log('hello'.get2()); 

但是到那时,箭头功能变得多余了。

我希望做一些魔术,包括将实例作为箭头函数的参数传递,并使用实例“ self”代替“ this”。 类似于hastebin.com/baxadaxoli.coffee,但没有“功能”。 例如,在分配过程中传递“自我”,而不通过某些magicBind操作创建函数。

var magicBind = (callback) => function (...args) {
    'use strict';
    return callback(this, args);
}

var log = (self, args) => {
  console.log('this: %o args: %o', self, args);
};

String.prototype.log = magicBind( log );

'hello'.log();

足够的魔法? ;)

编辑:但是,为什么您仍然坚持使用粗箭头。 即使您必须跳过循环来实现所需的功能。 只是为了从您的.min.js文件中删除一些字符

/ * logget更合适,

并且console.log()没有返回值的函数的结果是没有意义的; 如果该函数的唯一目的是调用console.log()本身,则更少* /

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM