zoukankan      html  css  js  c++  java
  • 任性,新建对象不用new

    先看最简单的一个例子:

     1 window.meng = window.meng || {};
     2 (function () {
     3 
     4     /**
     5      *
     6      * @param {Number}width
     7      * @param {Number}height
     8      * @param {String}color
     9      * @constructor
    10      */
    11     function CreateDiv(width, height, color) {
    12         this.oWidth = width;
    13         this.oHeight = height;
    14         this.oColor = color;
    15     }
    16 
    17     CreateDiv.prototype.render = function () {
    18         var div = document.createElement("div");
    19         div.style.width = this.oWidth + "px";
    20         div.style.height = this.oHeight + "px";
    21         div.style.backgroundColor = this.oColor;
    22         return div;
    23     };
    24     meng.CreateDiv = CreateDiv;
    25 })();
    1 (function () {
    2 
    3     var div=new meng.CreateDiv(100,100,"red");
    4     document.body.appendChild(div.render());
    5 })();

    上面是一个简单在页面添加div的例子。

    当去掉new,的时候在运行会出现

    但是我经常忘记,写new,又懒得去改,所以马虎人有马虎人的方法。

    “轮子代码”这样改写

     1 window.meng = window.meng || {};
     2 (function () {
     3 
     4     /**
     5      *
     6      * @param {Number}width
     7      * @param {Number}height
     8      * @param {String}color
     9      * @constructor
    10      */
    11     function CreateDiv(width, height, color) {
    12         this.oWidth = width;
    13         this.oHeight = height;
    14         this.oColor = color;
    15         if (!(this instanceof CreateDiv)) {
    16             return new CreateDiv(width, height, color);
    17         }
    18     }
    19 
    20     CreateDiv.prototype.render = function () {
    21         var div = document.createElement("div");
    22         div.style.width = this.oWidth + "px";
    23         div.style.height = this.oHeight + "px";
    24         div.style.backgroundColor = this.oColor;
    25         return div;
    26     };
    27     meng.CreateDiv = CreateDiv;
    28 })();

    就会发现不报错了。。╮(╯▽╰)╭

  • 相关阅读:
    Primary key and Unique index
    Hash unique和Sort unique
    Oracle索引扫描算法
    Oracle预估的基数算法
    PGA突破pga_aggregate_target限制
    aix ipcs使用说明
    开窗函数和聚合函数区别
    【39.66%】【codeforces 740C】Alyona and mex
    【81.82%】【codeforces 740B】Alyona and flowers
    Android SDK离线安装
  • 原文地址:https://www.cnblogs.com/chenluomenggongzi/p/5998103.html
Copyright © 2011-2022 走看看