更新JS类的属性基于其他属性

Updating properties of JS "class" based on other properties?

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

我对Javascript比较陌生,我正试图为我正在从事的游戏类型项目创建一个非常简单的物理引擎。为了做到这一点,我创建了我所理解的JS等效类,我可以为我想要的每个对象创建新的副本。问题是,我希望能够更新一个值,如x位置,并让这也更新东西,如x中间位置(x对象在屏幕上的中心)。我知道这可以通过使用对象文字和getter实现,但我希望能够基于屏幕上的内容实时创建新对象我不知道如何使用get来实现这个。下面是我要做的事情的总体思路:

var object = function (xPos, yPos, width, height) {
  this.xPos = xPos;
  this.yPos = yPos;
  function getXMid (xP) { return xP + width/2; }
  this.xMid = getXMid (this.xPos);
  function getYMid (yP) { return yP + height/2; }
  this.yMid = getYMid (this.yPos);
}
var ball = new object (10, 20, 50, 50);
ball.xPos = 50;
console.log (ball.xMid); // want this to output 75 instead of 45

您正在更改一个属性,并期望其他属性更新,不幸的是,当属性保存原始值时,它不会这样工作。

当你设置一个值

时,你可以使用setter、getter和一个函数来更新其他属性。

var object = function(xPos, yPos, width, height) {
    this._xPos  = xPos;
    this._yPos  = yPos;
    this.recalc = function() {
    	this.xMid = getXMid(this.xPos);
        this.yMid = getYMid(this.yPos);
    }
    
    Object.defineProperty(this, 'xPos', {
        get: function() {
            return this._xPos;
        },
        set: function(v) {
        	this._xPos = v;
        	this.recalc();
        }
    });
	Object.defineProperty(this, 'yPos', {
        get: function() {
            return this._yPos;
        },
        set: function(v) {
        	this._yPos = v;
        	this.recalc();
        }
    });
    
    function getXMid(xP) { return xP + width / 2; }
    
    function getYMid(yP) { return yP + height / 2; }
    
    this.recalc();
}
var ball = new object(10, 20, 50, 50);
ball.xPos = 50;
console.log (ball.xMid); // want this to output 75 instead of 45