实例代码“Ctrl+/”提示“F11/ESC”全屏 返回 格式化 恢复 运行
x
 
1
<!DOCTYPE html>
2
<html>
3
<head>
4
    <title>Accessor Properties Example</title>
5
    <script type="text/javascript">
6
7
        var book = {
8
            _year: 2004,
9
            edition: 1
10
        };
11
          
12
        Object.defineProperty(book, "year", {
13
            get: function(){
14
                return this._year;
15
            },
16
            set: function(newValue){
17
            
18
                if (newValue > 2004) {
19
                    this._year = newValue;
20
                    this.edition += newValue - 2004;
21
                
22
                }
23
            }
24
        });
25
        
26
        book.year = 2005;
27
        alert(book.edition);   //2
28
29
    </script>
30
</head>
31
<body>
32
    <p>Note: this example only works in browsers that have implemented the ECMAScript 5 <code>Object.defineProperty()</code> method (IE9 and Firefox 4).</p>
33
</body>
34
</html>