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);

 

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

相关文章:

  • 2022-12-23
  • 2022-01-03
  • 2022-12-23
  • 2018-11-30
  • 2022-12-23
  • 2021-09-14
  • 2022-12-23
  • 2021-08-08
猜你喜欢
  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案