在窃取函数中用作用域安全的构造函数

 1 function Polygon(sides) {
 2     if (this instanceof Polygon) {
 3         this.sides = sides;
 4         this.getArea = function() {
 5             return 0;
 6         };
 7     } else {
 8         return new Polygon(sides);
 9     }
10 }
11 
12 function Rectangle(width, height) {
13     Polygon.call(this, 2);
14     this.width = width;
15     this.height = height;
16     this.getArea = function() {
17         return this.width * this.height;
18     };
19 }
20 
21 var rect = new Rectangle(5, 10);
22 console.log(rect.sides);

 以上输出会报undefined

 

 

 1 function Polygon(sides) {
 2     if (this instanceof Polygon) {
 3         this.sides = sides;
 4         this.getArea = function() {
 5             return 0;
 6         };
 7     } else {
 8         return new Polygon(sides);
 9     }
10 }
11 
12 function Rectangle(width, height) {
13     Polygon.call(this, 2);
14     this.width = width;
15     this.height = height;
16     this.getArea = function() {
17         return this.width * this.height;
18     };
19 }
20 
21 Rectangle.prototype = new Polygon();
22 
23 var rect = new Rectangle(5, 10);
24 console.log(rect.sides);

 

 这样就正确了,使用原型链

posted @ 2012-06-08 16:20  小猩猩君  阅读(200)  评论(0编辑  收藏  举报