在打字稿中访问类属性

时间:2020-04-23 16:13:30

标签: javascript node.js typescript

我有一个打字稿类,其构建方式如下

export default class myClass{

myns: any;

async initializing() {
…
this.myns = na.map(function (item) {
  return item["name"];
});

// here we have value 
console.log(this.myns);

}


search(test, input) {

input = input || "";
return new Promise(function (resolve) {
    let fuz= fuzzy.filter(input, this.myns);  //here I want to access myns but here it comes undefined in debug
    resolve(
      fuz.map(function (el) {
        return el.original;
      })
    );
});



}

}

我想访问函数myns中的search(在该函数中搜索是未定的,但在其内部有数据)搜索该怎么办?

不仅未定义mynsthis也未定义

1 个答案:

答案 0 :(得分:1)

尝试执行(resolve) => {而不是function (resolve) {,以便将其绑定到回调

编辑:

运行此代码对我有用:

class myClass {
  myns: any;

  async initializing() {
    this.myns = [{ name: 'test1' }, { name: 'test2' }].map(function (item) {
      return item["name"];
    });

    console.log(this.myns);
  }

  search(test, input) {
    input = input || "";

    return new Promise((resolve) => {
      console.log('test');
      console.log(this.myns);

      resolve();
    });
  }
}

const test = new myClass();

test.initializing();
test.search('lala', 'lala2');

如预期的那样,输出为:

[ 'test1', 'test2' ]
test
[ 'test1', 'test2' ]

您正在使用的模糊库是什么?