在类函数中访问`this`是未定义的

时间:2018-12-27 00:21:54

标签: javascript

我正在尝试在一个类中实现节流方法,该类将某些类属性作为第二个参数,但是由于this未定义,所以我无法访问该类属性。

我以一种更简单的方式复制了代码以演示该问题:

function someThrottleFunction(a, b) {
  // doesn't really matter what is in here
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
  }
  func = someThrottleFunction(() => {}, this.prop1.time);
}

let a = new cname({ time: 3000 });

您可以在此处查看实时代码错误演示:https://codesandbox.io/s/x7yqy933qq

对于如何以一种有效的方式重写它的任何建议,我们深表感谢。

2 个答案:

答案 0 :(得分:3)

问题是func在构造函数运行之前被分配给

function someThrottleFunction(a, b) {
  // doesn't really matter what is in here
}

class cname {
  constructor(prop1) {
    console.log('constructor running');
    this.prop1 = prop1;
  }
  func = (console.log('func being assigned to'), someThrottleFunction(() => {}, this.prop1.time));
}

let a = new cname({ time: 3000 });

您可以改为在构造函数的末尾赋值:

function someThrottleFunction(a, b) {
  // doesn't really matter what is in here
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
    this.func = someThrottleFunction(() => {}, this.prop1.time);
  }
}

let a = new cname({ time: 3000 });

答案 1 :(得分:1)

您似乎希望func成为一个函数:

function someThrottleFunction(a, b) {
  console.log(b)
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
  }
  func() { 
    someThrottleFunction(() => {}, this.prop1.time);
  }
}

let a = new cname({ time: 3000 });
a.func()

function someThrottleFunction(a, b) {
  console.log(b)
}

class cname {
  constructor(prop1) {
    this.prop1 = prop1;
  }
  func = () => { 
    someThrottleFunction(() => {}, this.prop1.time);
  }
}

let a = new cname({ time: 3000 });
a.func()