以下爲《Javascript設計模式》讀書筆記:
JavaScript中創建對象共有三種基本模式:門戶大開型(fully exposed),使下劃線表示方法或屬性的私有性和閉包創建是有成員。
1.門戶大開型
用一個函數作爲構造器,所有的屬性和方法都是公開的、可訪問的,使用this即可創建公用屬性。
var Book = function(isbn,title,author){ if(isbn == undefined) throw new Error('book constructor requires an isbn'); this.isbn = isbn; this.title= (title? title:‘No title specified'); this.author = (author?author:'No author specified'); } Book.prototype.display = function{ };
2.用命名規範區別私有成員
這種模式與門戶大開型對象創建模式相同,只是在一些方法和屬性的名稱前加了下劃線,以示其私用性。
var Book = function(isbn,title,author){ if(isbn == undefined) throw new Error('book constructor requires an isbn'); this._isbn = isbn; this._title= (title? title:‘No title specified'); this._author = (author?author:'No author specified'); } Book.prototype.display = function{ };
3.使用閉包實現私有成員
在Javascript中只有函數具有作用域,即在一個函數內部聲明的變量在函數外部無法訪問。爲創建私有屬性,需要在構造器函數的作用域中定義相應變量,這些變量可被定義於該作用域中的所有函數訪問。
var Book = function(newIsbn,newTitle,newAuthor){ var isbn,title,author; var checkIsbn = function (){ }; this.setIsbn = function(newIsbn){ isbn = newIsbn; }; this.getIsbn = function(){ return isbn; }; this.setTitle = function(newTitle){ title = newTitle; }; this.getTitle = function(){ return title; }; this.getAuthor = function(){ return author; }; this.setAuthor = function(newAuthor){ author = newAuthor; }; }; Book.prototype = { display:function(){ } };