【问题标题】:access Object property from same object method, this method is called inside class method [duplicate]从同一对象方法访问对象属性,该方法在类方法中调用[重复]
【发布时间】:2021-10-17 12:18:15
【问题描述】:

所以我有类 MyClass,它有方法 myFunction,这个方法接受对象数组,在这个对象中有方法 func,我想用 func 方法访问这个对象内部的这个方法索引或名称属性。怎么办?

const object = [{
    index: 1,
    name:"John",
    func: async(store) => {
        store[this.index] = "this text";
    }
}];

class MyClass {
    constructor() {
        this.store = {};
    }
    async myFunction(object) {
        for (let i in object) {
            await object[i].func(this.store);
        }
    }
}

const myClass = new MyClass();

(async() => {
    try {
        await myClass.myFunction(object);
        const store = myClass.store;
        console.log(store);
    } catch (err) {
        console.log(err);
    }
})();

【问题讨论】:

    标签: javascript object asynchronous arrow-functions


    【解决方案1】:

    这是一个working sandbox,其中包含您要求的解决方案。

    你要找的是这个:

    const object = [
      {
        index: 1,
        async func(x) {
          console.log(this.index);
        }
      },
      {
        index: 2,
        async func(x) {
          console.log(this.index);
        }
      }
    ];
    

    注意this的使用以及从箭头函数到常规函数的变化(也使用es6语法编写方法)

    【讨论】:

    • 仍然无法通过使用 this.index 访问 x.index 而不是 index:1 或 index:2 in object
    • 我更新了我的答案,提供了一个我认为可以解决您问题的代码的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多