// 1: 函数提升
test();
var test=function(){
console.log('我被调用了');
};
// test is not a function
// 注意一下 函数会提升到当前作用域的最顶部 优先级高于var
// 2:
function test(a,b,c){
console.log(arguments.length);
// 0
// 如何将类数组对象转换为数组 3种方法
// 1.Array.from();
console.log(Array.from(arguments));
// []
// 2.Array.prototype.slice.call(arguments,0)
console.log(Array.prototype.slice.call(arguments,0));
// []
// 3....拓展运算符
let arr=[...arguments];
console.log(arr);
// []
let params={
page:1,
pageSize:10
}
let obj={
...params
}
console.log(obj,'obj');
// { page: 1, pageSize: 10 } obj
}
// 3:
test(1,2,3,4,5)
console.log(this);//{} modules export 单独使用时this
function test(){
console.log(this,'函数');
// 函数中this指向global
}
test()
// 4:回调函数
function A(callback){
callback()
console.log('我是主函数');
}
function B(){
console.log('我是回调');
}
setTimeout(B,3000)
A(B)
// 按顺序执行
// 我是回调
// 我是主函数
// 我是回调
// 5:闭包
// 实现一个函数每调用一次 变量递减
// function A(){
// var a=10;
// function test(){
// a--;
// console.log(a);
// }
// return test
// }
// var res=test()
// console.log(res());
function test(){
var a=10;
function fn(){
a--;
console.log(a,'a');
}
return fn
}
var res=test();
// 要用新的变量来接收 因为函数被调用后垃圾回收站会回收 被销毁
// res()=test()()
console.log(res());
console.log(res());
console.log(res());
console.log(res());
// 闭包
// 1.嵌套函数
// 2.存在对外部函数变量的引用
// 3.变量可以被保存在内存中不会被垃圾回收回收
// 4.返回内部函数
// 优点:防止变量污染,内部维持变量可以做缓存;
// 缺点:变量不会被垃圾回收机制回收,造成内存泄露,造成性能问题
//1:
var o = {
a: 10,
b: {
a: 12,
fn: function(){
console.log(this.a);//12
console.log(this);// b:{} 函数b调用了fn() this指向b;
}
}
}
o.b.fn();
var o = {
a: 10,
b: {
fn: function(){
console.log(this.a);
// undefined 函数b调用的fn() 拿不到a:10;
console.log(this);
// this指向 函数b
}
}
}
o.b.fn();
// 2
var point = {
x : 0,
y : 0,
moveTo : function(x, y) {
// var that=this;
// 内部函数
var moveX = function(x) { //1
// that.x = x;
// this 指的是全局 因为全局调用了moveX 将moveX()中的x 此时是1 赋给全局的x
this.x = x;
};
// 内部函数
var moveY = function(y) { //1
// that.y = y;
this.y = y;
}
//全局调用了moveX() moveY();
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x); //0
console.log(point.y); //0
// 输出全局的x y;
console.log(x);//1
console.log(y);//1