【问题标题】:Javascript predefined local variables for inJavascript 为 in 预定义的局部变量
【发布时间】:2021-08-11 09:44:45
【问题描述】:

例如

function mount(cb) {
    this.payload = 5;
    this.items = [1,2,3];
    cb.apply(this);
}

function render() {
    var _this = this;
    this.items.map(function(num){
        return _this.payload + num
    })
}

mount(render);

是否可以在'mount'中为'render'预定义一个变量_this,不要使用函数args,我可以写什么

function render() {
    this.items.map(function(num){
        _this.payload + num
    })
}

_this举例,即为自定义函数预定义局部变量,每次调用都一样,即常量

【问题讨论】:

    标签: javascript ecma


    【解决方案1】:

    箭头函数将起作用,因为它保留了范围

    function render() {
        this.items.map((num) => {
            return this.payload + num
        })
    }
    

    也可以缩短:

    function render() {
        this.items.map(num => this.payload + num)
    }
    

    阅读更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      相关资源
      最近更新 更多