闭包/this练习题

1、

var num = 1,
    obj = {
        num: 2,
        fn: (function (num) {
            this.num *= 2;
            num += 2;

            return function () {
                this.num *= 3;
                num ++;
                console.log(num);
            }
        })(num)
    };
var fn = obj.fn;
fn();
obj.fn();
console.log(num, obj.num);
练习题1

2、

var foo = 1;
function bar() {
    if(!foo){
        var foo = 100;  // 不管条件成不成立,都要进行变量提升
    }
    console.log(foo);
}
bar();  // 100
练习题2

3、

var foo = 'hello';
(function (foo) {
    // 先形参赋值
    console.log(foo); //hello
    var foo = foo || 'world';
    // foo = foo
    console.log(foo);
})(foo);
console.log(foo);  // hello hello hello

逻辑或:第一项转布尔类型为true,就返回第一项的运算结果,反之,返回后面的运算结果
逻辑与:跟逻辑或相反
若两者都有时,先算逻辑与再算逻辑或,即逻辑与的优先级高
0||2&&false||3 -> 3
应用:

function fn(num, callback){
  // 若num没传值让他为0
  num = num || 0;
  // 若callback传递一个函数就执行
  callback && callback();
}

4、

var a = 9;
function fn() {
    a = 0;
    return function (b) {
        return b + a ++;
    }
}
var f = fn();
console.log(f(5));
console.log(fn()(5));
console.log(f(5));
console.log(a);
// 5 5 6 2
练习题4

5、

var ary = [1,2,3,4];
function fn(ary) {
    ary[0] = 0;
    ary = [0];
    ary[0] = 100;
    return ary;
}
var res = fn(ary);
console.log(ary); // [0, 2, 3, 4]
console.log(res); // [100]

6、

function fn(i) {
    return function (n) {
        console.log(n + (i++));
    }
}
var f = fn(10);
f(20); // 30
fn(20)(40); // 60 
fn(30)(50); // 80
f(30); // 41
练习题6

7、

var num = 10;
var obj = {num: 20};
obj.fn = (function (num) {
    this.num = num*3;
    num ++;
    return function (n) {
        this.num += n;
        num ++;
        console.log(num);
    }
})(obj.num);
var fn = obj.fn;
fn(5);
obj.fn(10);
console.log(num, obj.num);  // 22 23 65 30
练习题7

你可能感兴趣的:(闭包/this练习题)