我可以在没有对象函数调用的情况下得到(可能已计算)属性值

时间:2016-02-28 13:26:07

标签: javascript

我为也许微不足道的问题道歉,但我现在有点困惑。 这是我对Rectangle的定义:

<!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>

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

Thanx辅导

2 个答案:

答案 0 :(得分:2)

像这样:

{{1}}

答案 1 :(得分:2)

可以通过getters

完成
alert('foo');
相关问题