Javascript对象:这两个值有何不同

Javascript objects: how are these two values different?

本文关键字:两个 何不同 对象 Javascript      更新时间:2023-12-27

我是OOP的新手,我很难分辨为什么我为两个控制台日志获得不同的值。第一个日志给了我正确的高度值,第二个通过对象属性访问该值的日志告诉我高度为0。我还可以说,如果我在imageLoader.images[this.sprite]上运行控制台日志,在this.height = imageLoader.images[this.sprite]时运行player1.height(所以基本上我从每个值中删除了.height属性),第一个日志会正确地命名精灵,即使它已经动态更改,而第二个日志再次不正确,只命名对象在创建时分配的精灵(来自imageName参数)。

作为一点背景,构造函数从对象imageLoader中提取图像,每个实际图像都包含在以图像名称命名的属性中。我想通过每个新事物的高度属性来访问每个图像的高度。

function Thing(imageName) {
    this.sprite = imageName;
    this.height = imageLoader.images[this.sprite].height;
}
var player1 = new Thing ("face_right");
console.log(imageLoader.images[player1.sprite].height);
console.log(player1.height);

希望这在某种程度上是明确的。谢谢你看。

您没有显示任何会导致精灵更改的代码,但您似乎是在说您希望player1.height自动更新以反映当前精灵的高度,精灵可以在哪里动态更改?如果是这样,它将不会以当前的方式工作,因为您设置的this.height属性将只是一个基元数值,而不是对其他对象属性的引用。当sprite更新时,您需要添加代码来更改Thing实例的.height属性。

或者,使用.height()方法,而不是.height属性,或者如下所示将其称为.getHeight()

function Thing(imageName) {
    this.sprite = imageName;
    this.getHeight = function() {
        return imageLoader.images[this.sprite].height;
    }
}
var player1 = new Thing ("face_right");
console.log(player1.getHeight());