做用是执行构造函数,返回实例对象
function F() { this.name = "object" } var obj = new F();
上面例子是自定义一个构造函数,其最大的特色就是首字母大写,用new执行构造函数;
其中this,在new的执行下,表明了实例化后的对象,这个obj也就有name属性
注意点:若是不用new执行构造函数,那么this指向的是全局window数组
function F() { this.name = "object" } var obj = F(); console.log(obj); //undefined console.log(name); //object
有两种方式能够避免:app
function F() { this.name = "object" } F(); //TypeError: Cannot set property 'name' of undefined
function F() { if(!(this instanceof F)){ return new F(); } this.name = "object" } F();
function F() { if(!new.target){ return new F(); } this.name = "object" } F();
简单来讲:不加new执行,this就是window;加了new执行,那么this = Object.create(F.prototype),构建一个空对象,继承下F的原型函数
return的内容不是对象,则忽视,返回的时this对象this
function F() { this.name = "object" reutrn 123; } var obj = F(); //{name : "object"}
return的内容是对象时,则返回return的对象,(null除外)prototype
function F() { this.name = "object" reutrn {a : 123}; } var obj = F(); //{a : 123}
前提是使用了new来执行构造函数
利用上述原理咱们能够简单模拟一个new的函数code
function _new(constructor, params) { //将arguments对象转为数组 var args = [].slice.call(arguments); //1.取出参数中的构造函数,2.过滤args,剩下对构造函数有用的实参 var constructor = args.shift(); //构建空对象,并继承构造函数的原型 var context = Object.create(constructor.prototype); //1.借用构造函数,将context空对象赋给this,2.并args实参与构造函数参数一一对应对其赋值,3.造成完整的this对象 var result = constructor.apply(context, args); //这个是处理return返回对象时的状况 return (typeof result === "object" && result != null) ? result : context; } function P(n) { var a = 1; this.b = n; //return null; } var p = _new(P,123); console.log(p);