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);
这样就正确了,使用原型链