1,常用发送短信的闭包实现:

function sms() {
var count = 60;
return {
start: function() {
if(count == 0) {
count = 60;
document.getElementById("time").innerHTML = count;
return;
} else {
document.getElementById("time").innerHTML = count;
count--;
}
var that = this;
setTimeout(function() {
that.start();
}, 1000)
},
stop: function() {
count = 60;
}
}
}
var sms = sms();
sms.start();

2,匿名自执行函数 

var data= {
msg: "Helloween "
};
(function(dm){
console.info(dm.msg)
})(data);

3,封装

var person = function(){
//变量作用域为函数内部,外部无法访问
var name = "default"; return {
getName : function(){
return name;
},
setName : function(newName){
name = newName;
}
}
}(); print(person.name);//直接访问,结果为undefined
print(person.getName());
person.setName("abruzzi");
print(person.getName());

4,实现类和继承 

function Person(){
var name = "default"; return {
getName : function(){
return name;
},
setName : function(newName){
name = newName;
}
}
}; var p = new Person();
p.setName("Tom");
alert(p.getName());
var Jack = function(){};
//继承自Person
Jack.prototype = new Person();
//添加私有方法
Jack.prototype.Say = function(){
alert("Hello,my name is Jack");
};
var j = new Jack();
j.setName("Jack");
j.Say();
alert(j.getName());

  

05-11 16:09