Javascript中new的疑惑

来源:互联网 发布:c语言变长参数传递 编辑:程序博客网 时间:2024/05/17 23:44
// 加不加new结果都一样var obj = new Function('var temp = 100;this.temp = 200;return temp + this.temp;');alert(typeof(obj)); // functionalert(obj()); // 300var obj = Function('var temp = 100;this.temp = 200;return temp + this.temp;');alert(typeof(obj)); // functionalert(obj()); // 300

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 alert(typeof num1); // object alert(typeof num2); // number alert(typeof bool1); // object alert(typeof bool2); // boolean 

或者
function person(name,age){this.name=name;this.age=age;}var p1=person('zhangsan',30);alert(p1);//undefinedvar 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的。