javascript中的物件導向,javascript物件導向
相信大家對javascript中的物件導向寫法都不陌生,那還記得有幾種建立對象的寫法嗎?相信大家除了自己常寫的都有點模糊了,那接下來就由我來幫大家回憶回憶吧!
1. 建構函式模式
通過建立自訂的建構函式,來定義自訂物件類型的屬性和方法。
function cons(name,age){ this.name = name; this.age = age; this.getMes = function(){ console.log(`my name is ${this.name},this year ${this.age}`); }}var mesge = new cons('will',21);mesge.getMes();
2. 原廠模式
該模式抽象了建立具體對象的過程,用函數來封裝以特定介面建立對象的細節
function cons(name,age){ var obj = new Object(); obj.name = name; obj.age = age; obj.getMes = function(){ console.log(`my name is ${this.name},this year ${this.age}`); } return obj;}var mesge = cons('will',21);mesge.getMes();
3. 字面量模式
字面量可以用來建立單個對象,但如果要建立多個對象,會產生大量的重複代碼
var cons = { name: 'will', age : 21, getMes: function(){ console.log(`my name is ${this.name},this year ${this.age}`); }}cons.getMes();
4. 原型模式
使用原型對象,可以讓所有執行個體共用它的屬性和方法
function cons(){ cons.prototype.name = "will"; cons.prototype.age = 21; cons.prototype.getMes = function(){ console.log(`my name is ${this.name},this year ${this.age}`); }}var mesge = new cons();mesge.getMes();var mesge1 = new cons();mesge1.getMes();console.log(mesge.sayName == mesge1.sayName);//true
5. 組合模式
最常見的方式。建構函式模式用於定義執行個體屬性,而原型模式用於定義方法和共用的屬性,這種組合模式還支援向建構函式傳遞參數。執行個體對象都有自己的一份執行個體屬性的副本,同時又共用對方法的引用,最大限度地節省了記憶體。該模式是目前使用最廣泛、認同度最高的一種建立自訂對象的模式
function cons(name,age){ this.name = name; this.age = age; this.friends = ["arr","all"];}cons.prototype = { getMes : function(){ console.log(`my name is ${this.name},this year ${this.age}`); }}var mesge = new cons("will",21);var mesge1 = new cons("jalo",21);console.log(mesge.friends);mesge.friends.push('wc'); //還可以運算元組哈O(∩_∩)O!console.log(mesge.friends);console.log(mesge1.friends);mesge.getMes();mesge1.getMes();console.log(mesge.friends === mesge1.friends);console.log(mesge.sayName === mesge1.sayName);
最後在告訴你個秘密,ES6引入了類(Class),讓對象的建立、繼承更加直觀了
// 定義類class Cons{ constructor(name,age){ this.name = name; this.age = age; } getMes(){ console.log(`hello ${this.name} !`); }}let mesge = new Cons('啦啦啦~',21);mesge.getMes();
在上面的程式碼片段裡,先是定義了一個Cons類,裡面還有一個constructor函數,這就是建構函式。而this關鍵字則代表執行個體對象。
而繼承可以通過extends關鍵字實現。
class Ctrn extends Cons{ constructor(name,anu){ super(name); //等同於super.constructor(x) this.anu = anu; } ingo(){ console.log(`my name is ${this.name},this year ${this.anu}`); }}let ster = new Ctrn('will',21);ster.ingo();ster.getMes();
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援幫客之家!