JavaScript重构(五):利用原型和闭包,完成组件方法
Java代码
var Player = (function(){
Player = function(){ //这只是个空壳
throw new Error("Can not instantiate a Player object.");
};
Player.MIN_EXTENDED_TIME = 1;
Player.MAX_EXTENDED_TIME = 3;
Player._player = false;
Player.getInstance = function(){
if(!Player._player){
alert("Init...");
Player._player = {
_name : name,
setName : function(name){
this._name = name;
},
toString : function(name){
return "Player: " + this._name;
}
};
}
return Player._player;
};
return Player; //把修缮完工的Player这个组件方法返回
})();
//var player = new Player(); //new Player()会抛出异常
var player1 = Player.getInstance();
var player2 = Player.getInstance();
player2.setName("RealPlayer");
alert(player2.toString()); //输出RealPlayer
终于要定义一个组件方法了,利用原型来实现。看看这样如何:
Java代码
function Player(name){
Player.MIN_EXTENDED_TIME = 1;
Player.MAX_EXTENDED_TIME = 3;
this._name = name;
};
Player.prototype.setName = function(name){
this._name = name;
};
Player.prototype.toString = function(){
return "Player: " + this._name;
};
var player = new Player("WindowsMediaPlayer");
alert(player.toString()); //输出WindowsMediaPlayer
player.setName("RealPlayer");
alert(player.toString()); //输出RealPlayer
alert(Player.MAX_EXTENDED_TIME);
恩,有封装、有常量、也有复写了Object的toString方法,至于继承之类的事情,咱们后面再说,初看看还不错。可是这样的组件方法定义不够优雅,也不够直观,方法都是放在独立的位置定义的,并没有和最开始的组件方法放置在一起,如果能像Java那样定义岂不更好?
对了,可以用闭包来实现。试试看吧:
Java代码
function Player(name){
Player.MIN_EXTENDED_TIME = 1;
Player.MAX_EXTENDED_TIME = 3;
this._name = name;
this.setName = function(name){
this._name = name;
};
this.toString = function(){
return "Player: " + this._name;
};
};
var player = new Player("WindowsMediaPlayer");
alert(player.toString()); //输出WindowsMediaPlayer
player.setName("RealPlayer");
alert(player.toString()); //输出RealPlayer
alert(Player.MAX_EXTENDED_TIME);
不像Groovy里面,闭包做了很大程度上的强化,包括新的语法的支持;JavaScript的闭包是很简单的闭包,它没有特殊的需要额外学习的语法,任意一个function,里面只要包含未绑定变量,这些变量是在function所属的上下文环境中定义的,那么,这个function就是闭包。顺便罗嗦一句,和闭包相反的,不正是不包含任何未绑定变量的函
相关新闻>>
- 发表评论
-
- 最新评论 更多>>