標籤:
《javascript進階編程》裡對new操作符的解釋:
new操作符會讓建構函式產生如下變化:
1. 建立一個新對象;
2. 將建構函式的範圍賦給新對象(因此this就指向了這個新對象);
3. 執行建構函式中的代碼(為這個新對象添加屬性);
4. 返回新對象
/*Constr:建構函式args:初始化參數*/function newOperator(Constr, args) { var thisValue = Object.create(Constr.prototype); // 以建構函式的原型對象建立一個新對象 var result = Constr.apply(thisValue, args);//把建構函式的this指向新對象,並為新函數添加新屬性 if (typeof result === ‘object‘ && result !== null) { return result; // 返回新對象 } return thisValue;}
看看這段代碼的結果
var a=5;function test(){ a=0; alert(a); alert(this.a); var a; alert(a);}test();new test();0500undefined0
再看看這段代碼的結果
var a=5;function test(){ this.a=0; alert(a); alert(this.a); var a; alert(a);}test();new test();undefined0undefinedundefined0undefined
這段代碼可以解釋為定義var a;那麼a就是函數的局部變數,只能在他的使用中的物件裡面找,當執行test()時,this.a相當於window.a;當執行new test()時,this.a這相當於新對象的屬性,而a還是test函數的局部變數,跟新對象沒關係
js中new建構函式的研究