任性,新建对象不用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 })();

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

原文地址:https://www.cnblogs.com/chenluomenggongzi/p/5998103.html