以下为《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(){ } };