微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。