公私有变量
回调函数的作用
回调函数可以减少全局变量的数量
从而达到优化的效果
回调函数:把函数当参数传进
DOM事件回调函数
定时器异步回调
<button></button>
var btn=document.getElementsByTagName("button")[0];
btn.onclick=function(){
console.log("我的名字叫卡卡西");
}
和定时器相似的东西
延时器
setTimeout(function(){
alert("我的名字叫卡卡西");
},2048);
定义了函数但是没有调用最终却执行了
案例
1.
function x(value){
alert(value);
}
x("我的名字叫卡卡西");
function y(content,value){
content(value);
}
y(x,"我的名字我爱罗");
2.
function x(content,value){
content(value);
}
x(function(y){
alert(y);
},"我的名字叫卡卡西");
// 私有变量,顾名思义就是私自的变量,外部无法访问
// 公有变量,外部可以访问
function content(){
var value="我的名字叫卡卡西"; //私有变量
this.world="成为火影"; //公有变量
}
var content=new content;
console.log(content.value); //undefined
console.log(content.world); //成为火影
解决方法
function Content(){
var x = function(){
console.log("我的名字叫卡卡西");
}
this.y = function(){
console.log("我的名字叫我爱罗");
}
}
var content = new Content();
content.y();
content.x();
- ##
特权方法
// 变量的链式作用域
// 全局作用域 局部作用域
// var content="我没咋"
// function value(){
// alert(content);
// }
// value();
// function content(){
// var value="我的名字叫卡卡西";
// }
// console.log(value);
// function x(){
// var content="我的名字叫卡卡西";
// function y(){
// var content="我的名字叫我爱罗";
// console.log(content);
// }
// y();
// }
// x(); //我的名字叫我爱罗
// 链式作用域
// x内部的局部变量对y是可见的,但是呢,y内部的变量对x来说,就是不可见的
// 子级会一层一层向外寻找
// 特权方法
// 某些情况下,如果我们呢想在函数外部访问私有变量或者私有函数,就可以通过特权方法
// 构造函数
// 构造函数里面,通过我们新开拓的一个对外可见的公共接口(公有函数),通过这个公有函数找到内部私有变量或者函数
// function Fn(){
// var content = "我的名字叫卡卡西";
// var x = function(){
// return "我的愿望是成为火影";
// }
// this.y = function(){
// return content+x();
// }
// }
// var fn = new Fn();
// console.log(fn.y());
- ##
公私有变量
var content=function(){
return "我的名字叫卡卡西";
}
console.log(content); //返回函数
console.log(content()); //返回我的名字叫卡卡西
var x=function(){
function y(){
console.log("我的名字叫卡卡西");
}
return y;
}
console.log(x()); //返回函数
x()(); //返回我的名字叫卡卡西
y();
y是属于x的,即y是x的内部函数,也叫私有函数,外部是无法访问的
var x=function(){
return function(){
return "我的名字叫卡卡西";
}
}
console.log(x()); //返回函数
console.log(x()()); //返回我的名字叫卡卡西