JavaScript-对象图仅在最后一个对象上应用功能可能存在吊装问题

问题描述

我创建了一个WebPage函数,该函数应作为一个类。

我有一个url键和WebPage对象值的映射,我想在每个对象上调用一个方法。称为startMonitoring方法应将interval设置为范围为每个对象的变量。

但是,间隔仅在最后一个对象上设置,其他所有对象在以后打印时将获得相同的输出

这是我的代码

export const startMonitoring = (websitesMap) => {
    websitesMap.forEach((website) => {
        website.startMonitoring();
    });
};
export function WebPage(url,checkTime) {
    // other variables
    this.scheduledTask;
    ...
    WebPage.prototype.startMonitoring = () => {
        this.scheduledTask = setInterval(async () => {
            // asynchronous work
        },checkTime * 1000);
    };
}

解决方法

之所以会这样,是因为每次创建新对象时都要设置原型。因此,所有实例都将访问您定义的最后一个实例。

现在,您将必须使用常规函数来访问正确的this

export const startMonitoring = (websitesMap) => {
    websitesMap.forEach((website) => {
        website.startMonitoring();
    });
};
export function WebPage(url,checkTime) {
    // other variables
    this.scheduledTask;
    this.checkTime = checkTime;
    ...
}
WebPage.prototype.startMonitoring = function() {
    this.scheduledTask = setInterval(async function() {
        // asynchronous work
    },this.checkTime * 1000);
};
,

就像Pointy所说的那样,使用原型可以工作:

const startMonitoring = (websitesMap) => {
  websitesMap.forEach((website) => {
      website.startMonitoring();
  });
};

function WebPage(url,checkTime) {
  // other variables
  this.scheduledTask;
  this.url = url;
  
  WebPage.prototype.startMonitoring = function() {
      this.scheduledTask = setInterval(async () => {
          console.log('hello',this.url);
      },checkTime * 1000);
  };
}

const websites = [new WebPage('#',1),new WebPage('#test',1)]
startMonitoring(websites);

此外,更改原型功能也应该起作用:

const startMonitoring = (websitesMap) => {
  websitesMap.forEach((website) => {
      website.startMonitoring();
  });
};

function WebPage(url,checkTime) {
  // other variables
  this.scheduledTask;
  this.url = url;
  
  this.startMonitoring = () => {
      this.scheduledTask = setInterval(async () => {
          console.log('hello',1)]
startMonitoring(websites);