js中prototype,constructor的理解


連看4篇前輩的文章,記錄一些知識點

  1. Javascript繼承機制的設計思想

  2. Javascript 面向對象編程(一):封裝

  3. Javascript面向對象編程(二):構造函數的繼承

  4. Javascript面向對象編程(三):非構造函數的繼承

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對象儲存需要共享的屬性和方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM