js產生對象的3種基本方式(原廠模式,建構函式模式,原型模式)

來源:互聯網
上載者:User

標籤:方法   字母   div   編程   function   注意   prot   測試   this   

1.原廠模式

function a(name){  var b = new object();    b.name = name;    b.say = function(){        alert(this.name);    }          return b    }

函數內部產生b對象並返回。

 

2.建構函式模式

function Person(name, url) {    //注意建構函式名第一個字母大寫  this.name = name;  this.url = url;  this.alertUrl = alertUrl;} function alertUrl() {  alert(this.url);}

因為每構造一個對象就會產生一個alertUrl方法,這樣太浪費資源空間,所以把alertUrl這個方法寫在全域以節省空間的,但這樣寫就違背了物件導向編程的初衷,下面的原型模式就更好一些。

 

3.原型模式

function Person(){  }Person.prototype.name = "bill";Person.prototype.address = "GuangZhou";Person.sayName = function (){       alert(this.name);  }var person1 = new Person();var person2 = new Person(); //測試代碼alert(person1.name);   // billalert(person2.name);    // billperson1.sayName();    //billperson2.sayName();    //billperson1.name = "666";alert(person1.name);   // 666alert(person2.name);    // billperson1.sayName();    //666person2.sayName();    //bill

  我們建立的每個函數都有prototype(原型)屬性,這個屬性其實是一個指標,指向一個對象。

  當構造一個person對象例如person1之後,它的預設name屬性就是bill。如果要改name值的話就要對person1.name操作。這隻是改了這個對象的name屬性。alert(person1.prototype.name)依然是彈出bill,即原型上的name屬性

 

註:這隻是本人學習的一些總結,如果有不對的地方還請各位大腿指正!

js產生對象的3種基本方式(原廠模式,建構函式模式,原型模式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.