不时更改类的属性

Change properties of a class from time to time

本文关键字:属性      更新时间:2023-09-26

我有两个函数。在第一个例子中,我把一个变量加100,然后加一个setInterval,这样函数就会在一段时间后重复。另一个函数是一个类,一个创建对象的控制器。我希望这个.x_origen在一段时间后通过添加aumento来增加,并重复它。然而,我在这里得到的是,第一个函数增加aumento,然后它结束,然后第二个函数开始。我该如何解决这个问题?

var aument = 0;
function aumento(){ 
    aument = aument + 100;
    return aument;
}
setInterval(function () {aumento()}, 1000/50);
function create_class_brick (x_origen_in, y_origen_in, x_final_in, y_final_in, mi_estado, mi_velocidad, mi_id){
    this.x_origen = x_origen_in + aumento();
    this.y_origen = y_origen_in;
    this.x_final = x_final_in + aumento();
    this.y_final = y_final_in;         
    this.estado = mi_estado;
    this.velocidad = mi_velocidad;
    this.id_elemento = mi_id;
    this.DESPLAZAR_LADRILLO  = desplazar_ladrillo;
    this.F0 = f0;
    this.F2 = f2;
    this.crear_ladrillo = crear_ladrillo;
    this.obtener_x_origen_ladrillo = obtener_x_origen_ladrillo;
    this.obtener_y_origen_ladrillo = obtener_y_origen_ladrillo;
    this.obtener_x_final_ladrillo = obtener_x_final_ladrillo;
    this.obtener_y_final_ladrillo = obtener_y_final_ladrillo;
}

关于如何等待初始调用的示例:

function brick (x_origen_in){
    this.x_origen = x_origen_in;
}
function aumento(brick){
    console.log(brick.x_origen);
    brick.x_origen += 100;
    setTimeout(aumento.bind(this, brick), 500);
}
var brick = new brick(100);
aumento(brick);

http://jsfiddle.net/x6c08u39/

无论何时访问,都可以使用Object.defineProperty动态生成值。

首先,让我们简化aument:的自动递增

var aument = 0;
function aumento(){ 
  aument += 100;
}
// The first argument for setInterval is the function to execute
// No need to figure out the interval value at runtime as there are no dynamic values
setInterval(aumento, 20); // 1000/50 === 20

现在让我们制作一个具有正确值的对象:

function create_class_brick (x_origen_in, y_origen_in, x_final_in, y_final_in, mi_estado, mi_velocidad, mi_id){
  Object.defineProperty(this, 'x_origen', {
    get: function () { return x_origen_in + aument; }
  });
  // Other stuff
  // ...  
}

快速测试:

> aument
34100
> var obj = new create_class_brick(23);
undefined
> obj.x_origen
161523
> obj.x_origen
167223
> obj.x_origen
172423