我可以在没有对象函数调用的情况下获取(可能是计算的)属性值吗?

Can I get (probably computed) property value without object function calling?

本文关键字:计算 属性 对象 函数调用 获取 情况下 我可以      更新时间:2023-09-26

对于可能微不足道的问题,我深表歉意,但现在我有点困惑。这是我对矩形的定义:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Fiddling</title>
        <script>
            function Rectangle() {
                this.left = arguments[0];
                this.top = arguments[1];
                this.right = arguments[2];
                this.bottom = arguments[3];
                this.width = function(){
                    return this.right - this.left;  
                }; 
                this.height = function() {
                    return this.bottom - this.top;  
                }
                this.Assign = function (ARectangle) {
                    this.left = ARectangle.left;
                    this.top = ARectangle.top;
                    this.right = ARectangle.right;
                    this.bottom = ARectangle.bottom;
                }   
            }
            var R = new Rectangle(100, 100, 400, 500);
            alert(R.width); //shows function definition
            alert(R.height); //shows function definition
            alert(R.width()); //shows proper value
            alert(R.height()); //shows proper value
        </script>
    </head>
    <body>
    </body>
</html>

这是(看似?)类似的例子,其中也有某种矩形 - DOMRectReadOnly,但属性宽度和高度显然不是函数。我想知道,他们是如何完成引入只读属性(宽度和高度)的,这可能是边框之间的差异 - 因此也是函数之间的差异。我也想拥有这些漂亮的形状属性。;-)

感谢辅导

它可以通过getters完成:

Object.defineProperty(this, 'width', {
    get : function(){
        return this.right - this.left;
    }
});
Object.defineProperty(this, 'height', {
    get: function(){
        return this.bottom - this.top;
    }
})

像这样:

Object.defineProperties(this, {
    width: {
        get: function(){
            return this.right - this.left;  
        },
    },
});