javascript中的面向對象

相信你們對javascript中的面向對象寫法都不陌生,那還記得有幾種建立對象的寫法嗎?相信你們除了本身常寫的都有點模糊了,那接下來就由我來幫你們回憶回憶吧!javascript

1. 構造函數模式

經過建立自定義的構造函數,來定義自定義對象類型的屬性和方法。java

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. 工廠模式

該模式抽象了建立具體對象的過程,用函數來封裝以特定接口建立對象的細節es6

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. 組合模式

最多見的方式。構造函數模式用於定義實例屬性,而原型模式用於定義方法和共享的屬性,這種組合模式還支持向構造函數傳遞參數。實例對象都有本身的一份實例屬性的副本,同時又共享對方法的引用,最大限度地節省了內存。該模式是目前使用最普遍、認同度最高的一種建立自定義對象的模式this

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關鍵字則表明實例對象。prototype

而繼承能夠經過extends關鍵字實現。code

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();

好了,此次的分享就到這了,喜歡的朋友能夠收藏哦(關注我也是能夠滴O(∩_∩)O)!!!對象

相關文章
相關標籤/搜索