連看4篇前輩的文章,記錄一些知識點
1. constructor
在Javascript語言中,new命令后面跟的不是類,而是構造函數(constructor)。
創建一個叫Student的構造函數,表示學生對象的原型
function Student(name){
this.name = name;
}
順便帶一下js中this的用法
Javascript 的 this 用法
對這個構造函數使用new,會生成Student的實例
var st1 = new Student("lilei")
console.log(st1.name) // lilei
此時st1 會自動含有一個屬性constructor,指向構造函數
console.log(st1.constructor == Student) //true
用構造函數生成實例對象(使用new),有一個缺點,那就是無法共享屬性和方法
比如說有同學韓梅梅和同學李雷,他們共同在太陽班
function Student(name){
this.name = name;
this.class = "sun";
}
var st1 = new Student("lilei")
var st2 = new Student("hanmeimei")
輸出二人的班級
console.log(st1.class)//sun
console.log(st2.class)//sun
班級改名,修改李雷的班級為月亮班
韓梅梅的班級名稱沒有發生變化,依然是sun(太陽班)
st1.class = "moon"
console.log(st1.class) //moon
console.log(st2.class) //sun
所以,構造函數中的共有屬性無法做到數據共享,要做到數據共享,需要用到prototype
2. prototype
構造函數設置有prototype屬性,屬性中包含一個對象,需要共享的屬性和方法,放在prototype對象里
。不需要共享的屬性和方法,放在構造函數里
將上述例子改寫
function Student(name){
this.name = name;
}
Student.prototype = {class : "sun"}
var st1 = new Student("lilei")
var st2 = new Student("hanmeimei")
st1.prototype.class = "moon"
console.log(st1.class) //moon
console.log(st2.class) //moon
每一個實例都有一個constructor屬性,默認調用prototype的constructor屬性
st1.constructor = st1.prototype.constructor
總結:
constructor儲存不需要共享的屬性和方法,而prototype對象儲存需要共享的屬性和方法