闭包是有权访问另一个函数作用域的变量的函数。
举个例子:
function bibao(){
function xiaoyi(){
console.log("被调用了");
}
return xiaoyi();
}
var bb = new bibao();
bb();
向闭包中传递数据
function bibao(){
function xiaoyi(str){
console.log(str);
}
return xiaoyi;
}
var bb = new bibao();
bb("被调用了");
全局函数的闭包书写
!(function(){
XiaoYi = function(val){
this.name = val;
this.getName = function(){
return this.name;
}
};
})();
console.log(XiaoYi);
var xy = new XiaoYi('小乙');
console.log(xy.getName());
闭包全局函数的扩展
!(function(){
//console.log(this);
XiaoYi = function(val){
this.name = val;
this.getName = function(){
return this.name;
}
};
})();
XiaoYi.prototype.getMName = function() {
return this.name;
};
console.log(XiaoYi);
var xy = new XiaoYi('小乙');
console.log(xy.getName());
console.log(xy.getMName());
需要注意的是: