zoukankan      html  css  js  c++  java
  • 在窃取函数中用作用域安全的构造函数

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

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

  • 相关阅读:
    做题总结
    关于SQLSERVER中用SQL语句查询的一些个人理解
    关于SQLSERVER联合查询一点看法
    C#中怎样实现序列化和反序列化
    java内部类的使用
    C#抽象类
    匿名类
    Foreach能够循环的本质
    C#索引器
    深入了解接口的使用
  • 原文地址:https://www.cnblogs.com/qzsonline/p/2541960.html
Copyright © 2011-2022 走看看