JavaScript 建立對象

來源:互聯網
上載者:User

標籤:type   產生   on()   rip   工廠   name   組合   javascrip   好的   

有三種基本的方式可以建立對象: 原廠模式、建構函式模式和原型模式

原廠模式:

function createPerson(name, age) {    var o = new Object();    o.name = name;    o.age = age;    o.getName = function() {        alert(this.name);    };        return o;       }var person1 = createPerson(‘james‘, 18);

 構造模式

function Person(name, age) {this.name = name;this.age = age;this.sayName = function() {alert(this.name);};}var person1 = new Person(‘james‘, 18);

 原型模式

function Person() {};    Person.prototype.name = ‘james‘;    Person.prototype.age = 18;    Person.prototype.getName = function() {    alert(this.name);};var person1 = new Person();

理解原型對象:

當定義建構函式Person時,會自動產生一個Person的原型對象Person.prototype;

Person.prototype中同時自動產生屬性constructor指向Person;

注意: 如果用對象字面量重新定義原型對象時,需要添加屬性constructor指向建構函式;

 

原廠模式每次都會生產出一個執行個體返回,類和封裝的實現沒有達到;

建構函式模式每次建立一個執行個體,其中的共通方法(函數)都會產生一個新的執行個體;

原型模式未實現每個執行個體得私人屬性;

 

因此,最好的建立對象的模式為:

組合使用建構函式模式和原型模式

function Person(name, age) {    this.name = name;    this.age = age;    this.friends = [];}Person.prototype = {    constructor: Person,    sayName: function() {        alert(this.name);    }};var Person1 = new Person(‘james‘, 18);

 

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.