Javascript中new

// 加不加new结果都一样
var obj = new Function('var temp = 100;this.temp = 200;return temp + this.temp;');
alert(typeof(obj)); // function
alert(obj()); // 300 var obj = Function('var temp = 100;this.temp = 200;return temp + this.temp;');
alert(typeof(obj)); // function
alert(obj()); // 300
推荐使用==> var obj=function(){var temp = 100;this.temp = 200;return temp + this.temp;}
alert(typeof(obj)); // function
alert(obj()); // 300
var d=new Date();
alert(d);
var d=Date();
alert(d);
var reg1 = new RegExp('^hello$');
var reg2 = RegExp('^hello$');
reg1.test('hello'); // true
reg2.test('hello'); // true
console.log(typeof reg1); // object
console.log(typeof reg2); // object
 测试发现使用或不使用new,最后返回的都是正则对象,且typeof它们都是object。下面都情况又不一样了
var str1 = new String(1);
var str2 = String(1);
var num1 = new Number('1');
var num2 = Number('1');
var bool1 = new Boolean(1);
var bool2 = Boolean(1); alert(typeof str1); // object
alert(typeof str2); // string 其实这里的String继承了Object,具有所有new出来的string的属性和方法
alert(typeof num1); // object
alert(typeof num2); // number
alert(typeof bool1); // object
alert(typeof bool2); // boolean

//或者 当自己定义的构造函数时,只能通过new去调用

function person(name,age){
this.name=name;
this.age=age;
}
var p1=person('zhangsan',30);
alert(p1);//undefined var p2=new person('zhangsan',30);
alert(p2);//object

JavaScript是一门基于原型的语言,但它却拥有一个 new 操作符使得其看起来象一门经典的面对对象语言。那样也迷惑了程序员,导致一些有问题的编程模式。其实你永远不需要在JavaScript使用 new Object()。用字面量的形式{}去取代吧。不要使用 new Array() ,而代之以字面量[]。JavaScript中的数组并不象Java中的数组那样工作的,使用类似Java的语法只会让你糊涂。不要使用
new Number, new String, 或者 new Boolean。这些的用法只会产生无用的类型封装对象。不要使用 new Function 去创建函数对象。用函数表达式更好。比如:frames[0].onfocus = new Function("document.bgColor='antiquewhite'") ;

应该frames[0].onfocus = function () {document.bgColor = 'antiquewhite';};

当你这样写的时候

myObj = new function () {
this.type = 'core';
};

你应该

myObj = {
type: 'core'
};

原则很简单: 唯一应该要用到new操作符的地方就是调用一个构造器函数的时候。当调用一个构造器函数的时候,是强制要求使用new的。

上一篇:基于HTML5 Canvas 实现商场监控


下一篇:AngularJS in Action读书笔记5(实战篇)——在directive中引入D3饼状图显示