JavaScript创建对象的基本方式

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值