简体   繁体   English

有没有更有效的方式组合这些对象?

[英]Is there a more efficient way to combine these objects?

I am working on a project that involves creating 2 timers. 我正在从事一个涉及创建2个计时器的项目。 The styles are different, however, the operations of both timers are very similar. 样式不同,但是两个计时器的操作非常相似。 I have created 2 different objects for this, but I was wondering if there is a more efficient way to refactor this and avoid repetition? 我为此创建了2个不同的对象,但是我想知道是否有更有效的方法来重构它并避免重复?

var timer1 = { 
  started: false, 
  minutes: 0,   
  seconds: 0, 
  interval: null,
  init: function() {
    var self = this;
    this.interval = setInterval(function() { 
      self.intervalCallback.apply(self); 
    }, 1000);
    // ...
}

var timer2 = { 
  timer2Started: false,
  timer2Minutes: 0, 
  timer2Seconds: 0,
  interval: null,
  init: function() { 
    var newTimer = this;
    this.interval = setInterval(function() { 
      self.intervalCallback.apply(newTimer); 
    }, 1000);
    // ...
}

$(document).ready(function() { 
  timer1.init(); 
  timer2.init(); 
});

You can use a single object and assign to 2 variables like this 您可以使用一个对象并分配给2个这样的变量

var timer = { 
  started: false, 
  minutes: 0,   
  seconds: 0, 
  interval: null,
  init: function() {
    var self = this;
    this.interval = setInterval(function() { 
      self.intervalCallback.apply(self); 
    }, 1000);
    // ...
}

var timer1 = timer, timer2 = timer;

$(document).ready(function() { 
  timer1.init(); 
  timer2.init(); 
});

Hope this helps. 希望这可以帮助。

You could use the Object.assign function. 您可以使用Object.assign函数。

Your code should look like this: 您的代码应如下所示:

var timer1 = { 
    started: false, 
    minutes: 0,   
    seconds: 0, 
    interval: null,
    init: function() {
        var self = this;
        this.interval = setInterval(function() { 
            self.intervalCallback.apply(self); 
        }, 1000);
        // ...
    }
};

var timer2 = Object.assign({}, timer1);  

In this way, timer1 and timer2 are 2 different objects. 这样,timer1和timer2是2个不同的对象。 If you write just timer2 = timer1, timer1 and timer2 will reference to the same object (timer1). 如果仅编写timer2 = timer1,则timer1和timer2将引用同一对象(timer1)。

That's because objects in the JavaScript are being copied by reference, not by value. 这是因为JavaScript中的对象是按引用而不是按值复制的。 The Object.assign function creates a new instance of the object. Object.assign函数创建该对象的新实例。

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

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