zoukankan      html  css  js  c++  java
  • 怎样在数组处理方法中使用this

    回调函数中的this不做处理的话, this仍然会指向window, 解决方法有两种. 

    第一种: 使用另一个变量固定this, 适用于在对象方法中使用的情况.

    var obj = {
        arr: [1,2,3],
        powerArr: function(){
            var self = this;
            self.arr = self.arr.map(function (item) {
                console.log(self);
                return item**2;
            });
        }
    };
    
    obj.arr; // [1,2,3]
    obj.powerArr(); // Object;
    obj.arr; // [1, 4, 9]

    下面是实际执行结果: 

    第二种: 将this作为数组处理方法的第二个参数传递进去

    var obj = {
        arr: [1,2,3],
        powerArr: function(){
            this.arr = this.arr.forEach(function(item){
                console.log(this);
                console.log(item**2);
            }, this);
        }
    };

  • 相关阅读:
    3月30日
    3月29日
    3月26日
    3月24
    3月22日
    3月20日
    博弈论基础
    $burnside$引理与$pacute olya$定理
    min-max容斥
    模板
  • 原文地址:https://www.cnblogs.com/aisowe/p/11660740.html
Copyright © 2011-2022 走看看