js設計模式精講系列

來源:互聯網
上載者:User

很久沒逛園子了,忙於工作,閑話少說,進入正題。

1:構造模式(Constructor Pattern)

先講下js對象的3中建立方式:

var newObj = {};var newObj = Object.create(null);var newObj = new Object();

常用的是第一種和第三種。

接著講下給對象添加屬性和方法的四種方法:

1.Dot文法 即通過“.”點號添加給對象添加屬性和值newObj.someKey ="Hello javascript! i love u";擷取屬性值var key = newObj.someKey;2.方括弧文法newObj["someKey"] = "this is the second method!";var key = newObj["someKey"];這兩種是比較普遍的做法,ECMAScript3 編譯通過3.Object.definePropertyObject.defineProperty(newObj,"someKey",{      value:"好處在於可以對屬性做更多的行為動作",       writeable:true,       enumerable:true,       configurable:true});一種更通俗易懂的簡單寫法var defineProp = function ( obj, key, value ){  config.value = value;  Object.defineProperty( obj, key, config );};使用這種方式,我們建立一個空person 對象var person = Object.create(null);defineProp(person,"car","BMW");defineProp(person,"dateOfBirth","1988");defineProp(person,"hasbeard",true);等等4.Object.defineProperties如果說剛才只能設定一個屬性,這個可以設定多個屬性,請看下面Object.defineProperty(newObj,{      "someKey":{             value:"這是一些屬性",             writeable:true},       "anotherKey":{             value:"這是另外一 些屬性",             writeable:true}});說明:3,4在ECMAScript5下編譯通過可以用1或2的方式擷取3或4屬性或者方法,改成方法例子把 value:function(args){} 即可

使用這些方法能夠用來繼承,我們來做個小實驗,看如下代碼:

建立一個賽車手,繼承上面的person對象var driver = Object.create(person);添加一些新的屬性或方法defineProp(driver,"topSpeed","100mph");我們輸出日誌看下是否繼承了person的屬性console.log(driver.dateOfBirth);//output:1988在重新擷取新設定的屬性console.log(driver.topSpeed);//output:100mph

上面這些例子也告訴我們Js 沒有class的概念,但是支援Object特殊的建構函式,通過簡單地加首碼使用關鍵字“new”調用建構函式,我們可以告訴JavaScript我們希望用函數來表現得像一個建構函式、執行個體化一個新的對象與成員定義的函數。

簡單的介紹後,我們來看基本的構造器模式的寫法,如下:

function Car( model, year, miles ) {  this.model = model;  this.year = year;  this.miles = miles;}//注意這裡我們使用obj.protorype.newMethod 而不是Object.prototype是為了避免重定義原型對象Car.prototype.toString = function () {  return this.model + " has done " + this.miles + " miles";};// 用法:var civic = new Car( "Honda Civic", 2009, 20000 );var mondeo = new Car( "Ford Mondeo", 2010, 5000 );console.log( civic.toString() );console.log( mondeo.toString() );

上面的ToString()的單一實例,保證每台Car都能共用這個方法。這裡就是一個簡單的構造器模式。

下章講解:模組化模式

 

  

 

聯繫我們

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