如何正确更新 Object?

How to update an Object properly?

我有一个 object 发电机。它工作正常。

'use strict';
function Div(isim) {
    this.loc = document.getElementById(isim);
    var style = window.getComputedStyle(this.loc);
    this.width = style.getPropertyValue('width');
    this.height = style.getPropertyValue('height');
    this.left = style.getPropertyValue('left');
    this.top = style.getPropertyValue('top');
}

但后来我正在更新元素的属性

var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
console.log(d.left); //gives auto
console.log(d.width); //gives the right value

console.log(d.left)是错误的。我已经找到了修复它的方法但是它有点脏,我认为:

var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
d = new Div("d");
console.log(d.left); //gives the right value
console.log(d.width); //gives the right value

还有其他方法吗(我更喜欢一行)?不幸的是, 本人英文不好,如有问题,标题错误,请修改。

在您的函数中将 this.left 更改为

this.left = function () {
    return window.getComputedStyle(this.loc).getPropertyValue('left');
}

然后在您的通话中将其更改为

console.log(d.left());

该值已缓存,因此您需要重新计算。

function Div(isim) {
    this.loc = document.getElementById(isim);
    var style = window.getComputedStyle(this.loc);
    this.width = style.getPropertyValue('width');
    this.height = style.getPropertyValue('height');
    this.left = style.getPropertyValue('left');
    this.top = style.getPropertyValue('top');
    this.getStyle = function (prop) {
        return style.getPropertyValue(prop);
    }.bind(this);
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
console.log(d.getStyle('left'));
console.log(d.getStyle('width'));

http://jsfiddle.net/s72vg53z/1/