JavaScript对象封装的三种方式
JavaScript中的封装特性 所谓封装,即限制外部对对象内部细节和数据的直接访问,仅暴露共有变量和函数。 在JavaScript中,创建对象以实现封装主要有三种途径:完全开放的门户大开型、基于命名约定的伪私有型,以及利用闭包实现的真正私有型。 1. 门户大开型是最基础的对象创建方式,其所有属性和方法均为共有状态,外部可直接访问。
var Book = function(name){
if(this.check(name)){
console.log("error");
throw new Error("name null");
}
this.name = name;
}
Book.prototype = {
check:function(name){
if(!name){
return true;
}
},
getName:function(){
return this.name;
}
}
var book = new Book("哈哈");
//output:哈哈 哈哈
console.log(book.name,book.getName());
上述示例展示了门户大开型的典型特征,外界能够直接读取对象的属性和调用方法。值得注意的是,这里的属性和变量均通过"this"关键字进行定义。 2. 命名规范区分法是对门户大开型的改进,通过在私有变量或方法名前添加下划线"_"来标识私有性。然而,这并非真正的隐藏,若程序员刻意调用如_getName()的方法,依然可以访问这些成员,因此未能彻底隐藏数据。 3. 闭包创建真正的私有变量,该方法借助JavaScript中只有函数具备作用域的特性,在构造函数内部定义相关变量。这些变量可被该作用域内的所有函数访问。
var Book2 = function(name){
if(check(name)){
console.log("error");
throw new Error("name null");
}
name = name;
function check(name){
if(!name){
return true;
}
}
this.getName = function(){
return name;
}
}
Book2.prototype = {
display:function(){
//无法直接访问name
return "display:"+this.getName();
}
}
var book2 = new Book2("哈哈");
//output:undefined "哈哈" "display:哈哈"
console.log(book2.name,book2.getName(),book2.display());
观察此例结果可知,直接访问name将返回undefined。这与门户大开型形成鲜明对比:前者使用"this"创建变量,而本例使用"var"声明,使得name变量及check函数仅限于构造函数作用域内可见,外部无法直接触及。 尽管该方法解决了前两种方式的缺陷,但也存在弊端。在门户大开模式中,方法定义在原型对象上,无论生成多少实例,内存中仅保留一份方法副本;而在闭包模式下,每个新对象实例都会为私有变量和方法创建新的副本,从而消耗更多内存资源。
JavaScript中的继承机制 Book基类定义如下:
var Book = function(name){
if(this.check(name)){
console.log("error");
throw new Error("name null");
}
this.name = name;
}
Book.prototype = {
check:function(name){
if(!name){
return true;
}
},
getName:function(){
return this.name;
}
}
继承实现方法:
function extend(subClz,superClz){
var F = function(){}
F.prototype = superClz.prototype;
subClz.prototype = new F();
subClz.prototype.constructor = subClz;
subClz.superClass = superClz.prototype;
if(superClz.prototype.constructor == Object.prototype.constructor){
superClz.prototype.constructor = superClz;
}
引入空函数F作为中间桥梁,可避免直接实例化父类时触发父类构造函数的额外开销。此外,当父类构造函数需要参数时,若试图通过subClass.prototype = new superClass();来实现原型链继承及父类构造函数调用,则是不可行的。
subClz.superClass = superClz.prototype;
if(superClz.prototype.constructor == Object.prototype.constructor){
superClz.prototype.constructor = superClz;
}
添加以下三行代码后,子类无需再编写Book.call(this,name);,只需简单调用ArtBook.superClass.Constructor.call(this,name)即可实现相同效果。 同时,在子类重写父类方法时,也能方便地调用父类原有方法:
ArtBook.prototype.getName = functiion(){
return ArtBook.superClass.getName.call(this) + "!!!";
}
ArtBook子类定义:
var ArtBook = function(name,price){
ArtBook.superClass.Constructor.call(this,name);
this.price = price;
}
extend(ArtBook,Book);
ArtBook.prototype.getPrice = function(){
return this.price;
}
ArtBook.prototype.getName = function(){
return ArtBook.superClass.getName.call(this)+"!!!";
}