从班级内部调用道具

时间:2018-11-02 16:50:25

标签: javascript reactjs

我正在尝试从构造函数中访问this.url属性,但是我收到一条错误消息,指出它是未定义的。这似乎是正常的任务,使我无法前进。

export class Something {
  constructor() {
    this.url = 'domain.com';
  }
  static something(param) {
    const url = `${this.url}/dir/tofile`; // ${this.url} is showing as undefined
    ...
  }
}

1 个答案:

答案 0 :(得分:2)

A static method is shared between all instances of the class,并且无权访问特定实例的变量。

如果您希望该方法可以访问实例的唯一属性,则可以删除static关键字,然后在实例上而不是在类上调用它。

示例

class Something {
  constructor() {
    this.url = 'domain.com';
  }
  static something(param) {
    const url = `${this.url}/dir/tofile`;
    console.log(url);
  }
}

class SomethingElse {
  constructor() {
    this.url = 'domain.com';
  }
  somethingElse(param) {
    const url = `${this.url}/dir/tofile`;
    console.log(url);
  }
}

const se = new SomethingElse();

Something.something();
se.somethingElse();