講解之前,我們先來看一個栗子:
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');
大家覺得上面的函數, People('harrisking','23');和new People('bob','22');輸出的結果相同嗎?
答案是,完全的不同。
People('harrisking','23');
是執行這個函數;而new People('bob','22');
不僅是執行這個函數,還是將它作為構造函數去創建對象(如果不傳參數可以不加括號)。
一個函數前面加上new就是將它作為構造函數去創建對象。
這個對象中的屬性就是你在這個函數中給this賦的值,例如上面函數中的this.name
。值就是傳遞進去的參數。