zoukankan      html  css  js  c++  java
  • 创造特殊的构造函数——寄生构造函数模式

    当我们需要构造一个特殊的数据,我们可以通过寄生构造函数来实现。比如我们要格式化一个Array(简单举例),将其变成一个有“|”组成的字符串,我们可以这么做:

     1 window.onload = function() {
     2     var colors = new SpecialArray("red", "blue", "green");
     3 
     4     document.writeln(colors.toPipedString());    // red|blue|green 
     5 };
     6 
     7 function SpecialArray() {
     8     // 创建数组
     9     var values = new Array();
    10 
    11     // 添加值
    12     values.push.apply(values, arguments);
    13 
    14     // 添加方法
    15     values.toPipedString = function() {
    16         return this.join("|");
    17     };
    18 
    19     // 返回数组
    20     return values;
    21 }

    注:返回的对象与构造函数或者与构造函数的原型属性之间没有关系;也就是说,构造函数返回的对象与在构造函数外部创建的对象没有什么不同。为此,不能依赖 instanceof 操作符来确定对象类型。

  • 相关阅读:
    Redux
    React-Router常见API
    webpack的plugin原理
    Kubernetes核心原理笔记
    阿里云证书过期时间监测
    DRF
    一个TCP可以发送多少个请求
    jenkins exporter(收集jenkins构建结果)
    Kubernetes SDN
    Django REST framework API认证(包括JWT认证)
  • 原文地址:https://www.cnblogs.com/tinyTea/p/9923252.html
Copyright © 2011-2022 走看看