实例代码“Ctrl+/”提示“F11/ESC”全屏 返回 格式化 恢复 运行
x
 
1
<!DOCTYPE html>
2
<html>
3
<head>
4
    <title>Scope-Safe Constructors Example</title>
5
</head>
6
<body>
7
    <script type="text/javascript">
8
            
9
        function Polygon(sides){
10
            if (this instanceof Polygon) {
11
                this.sides = sides;
12
                this.getArea = function(){
13
                    return 0;
14
                };
15
            } else {
16
                return new Polygon(sides);
17
            }
18
        }
19
        
20
        function Rectangle(width, height){
21
            Polygon.call(this, 2);
22
            this.width = width;
23
            this.height = height;
24
            this.getArea = function(){
25
                return this.width * this.height;
26
            };
27
        }
28
        
29
        var rect = new Rectangle(5, 10);
30
        alert(rect.sides);   //undefined
31
32
33
34
    </script>
35
</body>
36
</html>
37