实例代码“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
        function Polygon(sides){
9
            if (this instanceof Polygon) {
10
                this.sides = sides;
11
                this.getArea = function(){
12
                    return 0;
13
                };
14
            } else {
15
                return new Polygon(sides);
16
            }
17
        }
18
        
19
        function Rectangle(width, height){
20
            Polygon.call(this, 2);
21
            this.width = width;
22
            this.height = height;
23
            this.getArea = function(){
24
                return this.width * this.height;
25
            };
26
        }
27
        
28
        Rectangle.prototype = new Polygon();
29
        
30
        var rect = new Rectangle(5, 10);
31
        alert(rect.sides);   //2
32
33
34
35
36
    </script>
37
</body>
38
</html>
39