在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  HTML/ 運(yùn) test()和 new test()的結(jié)果是 么 ?

運(yùn) test()和 new test()的結(jié)果是 么 ?

var a = 5; function test() {

a = 0; 
alert(a); 
alert(this.a); 
var a; 
alert(a);

}
求 運(yùn)行 test() 和 new test()的結(jié)果

test()的結(jié)果為 0 5 0
但對于 new test 的結(jié)果 本人還是不太懂 有認(rèn)識的大神 可以解答一下么

回答
編輯回答
憶往昔

主要的區(qū)別就是this的指向變了
直接調(diào)用test()時,this的指向是windowglobal
使用new調(diào)用 new test()時, this的指向變成被實例化的對象。

2017年2月6日 14:40
編輯回答
不討喜

當(dāng)你運(yùn)行 test() 時,代碼等價于:

var a = 5;

function test() {
    var a;
    a = 0;
    alert(a);
    alert(window.a);//瀏覽器端
    alert(a);
};

當(dāng)你運(yùn)行 new test() 時,是把 test 當(dāng)作構(gòu)造函數(shù)來用,這個時候,你首先要清楚 this 在構(gòu)造函數(shù)中的指向問題,看測試:

function f(){
    console.log(this);
    console.log(this instanceof f);
}
f();// window;false;
new f();// f {} ;true

當(dāng)作為構(gòu)造函數(shù)來使用的時候,函數(shù)內(nèi)的這個 this 就指向一個新的對象,這個對象是這個構(gòu)造函數(shù)的實例,如果這個構(gòu)造函數(shù)沒有 return 或者 new 構(gòu)造函數(shù)返回一個基本類型值的話,那這個 this 對象也是這個 new 構(gòu)造函數(shù)的返回值;書上的話就是:

以這種方式調(diào)用構(gòu)造函數(shù)實際上會經(jīng)歷以下4個步驟:
(1) 創(chuàng)建一個新對象;
(2) 將構(gòu)造函數(shù)的作用域賦給新對象(因此this 就指向了這個新對象);
(3) 執(zhí)行構(gòu)造函數(shù)中的代碼(為這個新對象添加屬性);
(4) 返回新對象。

回來看你的問題,new test() 代碼實際是這樣:

var a = 5;

function test() {
    var a;
    a = 0;
    alert(a);
    alert(this.a);
    alert(a);
};

let obj=new test();

當(dāng)執(zhí)行這句代碼時:

let obj=new test();

new test() 里的 this ,指向的就是你用 new test() 所返回的對象,在這里,就是 obj ,而這個對象,你給他定義 a 屬性了么?沒有!所以 this.a 返回 undefined;考慮下面代碼:

var a = 5;

function test() {
    var a;
    a = 0;
    alert(a);
    this.a=1;//新加
    alert(this.a);//返回1,因為前面給 this.a 賦值了
    alert(a);
};

let obj=new test();
console.log(obj.a);//1

最后的 log 出來的 obj.a 就證明了這個 obj 和你在 new test() 里面的 this 是同一個對象;

參考:JavaScript高級程序設(shè)計-第3版-中-注釋.pdf

2018年6月7日 00:10