简体   繁体   English

在 typescript 访问 class 属性

[英]Access class property in typescript

I've a typescript class which built like following我有一个 typescript class 构建如下

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;
      })
    );
});



}

}

I want to access myns inside the function search (in the function search is undfiend but inside init it have data) search how can I do it?我想在 function search中访问myns (在 function 搜索中是 undfiend 但在 init 中它有数据)搜索我该怎么做?

not just myns is undefined this is undefined also不只是myns是未定义的this也是未定义的

Try doing (resolve) => { instead of function (resolve) { so it will bind this to the callback尝试做(resolve) => {而不是function (resolve) {这样它将绑定到回调

EDIT:编辑:

Running this code worked for me:运行此代码对我有用:

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');

As expected the output was:正如预期的那样,output 是:

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

What is that fuzzy library you are using?您正在使用的那个模糊库是什么?

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

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