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

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

  • 相关阅读:
    【python】正则表达式
    Java 接口、抽象类
    设计模式之抽象工厂方法模式
    设计模式之工厂方法模式
    设计模式之单例模式
    pulltorefresh学习
    ProgressDialog使用
    android:descendantFocusability用法简析
    数据保存之File
    runOnUiThread学习
  • 原文地址:https://www.cnblogs.com/qzsonline/p/2541960.html
Copyright © 2011-2022 走看看