講解之前,我們先來看一個(gè)栗子:
function People(name,age){
this.name = name;
this.age = age;
this.sayHello = fucntion(){
console.log('hello',this.name);
}
}
People('harrisking','23');
new People('bob','22');
大家覺得上面的函數(shù), People('harrisking','23');和new People('bob','22');輸出的結(jié)果相同嗎?
答案是,完全的不同。
People('harrisking','23');是執(zhí)行這個(gè)函數(shù);而new People('bob','22');不僅是執(zhí)行這個(gè)函數(shù),還是將它作為構(gòu)造函數(shù)去創(chuàng)建對(duì)象(如果不傳參數(shù)可以不加括號(hào))。
一個(gè)函數(shù)前面加上new就是將它作為構(gòu)造函數(shù)去創(chuàng)建對(duì)象。
這個(gè)對(duì)象中的屬性就是你在這個(gè)函數(shù)中給this賦的值,例如上面函數(shù)中的this.name。值就是傳遞進(jìn)去的參數(shù)。