JavaScript建立對象之單例、工廠、建構函式模式

來源:互聯網
上載者:User

標籤:事件綁定   檢測   事件   java   方法   如何   執行函數   asc   實現   

// 單例模式 解決分組問題 讓每個對象有自己的命名空間
var person1 = {
  name: "icss";
  age: 25;
};

var person2 {
  name: "sas";
  age: 26
}
//原廠模式 實現同一事情的代碼 放在一個函數中 其實就是函數的封裝 體現了高內聚 低耦合
function createPerson(name, age) {
  var obj = {};
  obj.name = name;
  obj.age = age;
  obj.writejs = function() {
    console.log(this.name + "write js");
  }
return obj;
}
var p1 = createPerson("zhang", 26);
p1.writejs();

var p2 = createPerson("li", 26);
p1.writejs();

// 重載 js不同於java \c#等強語言

// 建構函式模式
function CreateJsPerson(name, age) {
  this.name = name;
  this.age = age;
  this.writeJs = function() {
    console.log(this.name + ‘write js‘);
  }
// 瀏覽器再把建立的執行個體預設的進行返回
}
var p1 = new CreateJsPerson(‘iceman‘, 25);
p1.writeJs();
var p2 = new CreateJsPerson(‘mengzhe‘, 26);
p2.writeJs();

// 檢測是否屬於類 需要用instanceof 而不能用 typeof(因為只能檢測基本的資料類型)
function Fn() {
  this.x = 100;
  this.getX = function() {
    console.log(this.x);
  };
}
var f1 = new Fn;
console.log(f1 instanceof Fn); // --> true
console.log(f1 instanceof Array); // --> false
console.log(f1 instanceof Object); // --> true

// this js中主要研究的就是this 全域的this是window 就是瀏覽器對象

//在JavaScript中主要研究的都是函數中this,但是並不是只有函數中才有this,全域的this是window。
//
//JavaScript中的this代表的是當前行為執行的主體,JavaScript中的context代表的是當前行為執行的環境。
//
//首先明確:this是誰,和函數在哪裡定義,在哪裡執行都沒有任何的關係,那麼如何區分this呢?
//
//函數執行,首先看函數名前面是否有".",有點話,"."前面是誰,this就是誰,沒有的話,this就是window;
//
//自執行函數中的this永遠是window;
//
//給元素的某一個事件Binder 方法,當事件觸發的時候,執行對應的方法,方法中的this是當前的元素。

JavaScript建立對象之單例、工廠、建構函式模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.