1.5 KiB
this
1
function fn2(){ console.log(this.n) var n='n' this.n=10 console.log(n) } var obj={fn2:fn2, n:1} fn2() obj.fn2() console.log(obj.n, window.n)
//undefined 'n' //1 'n' //10 10
2
function f(){console.log(this)}
var obj={ fn: (function(){ return this.f })(), f: function(){console.log(this)} } f() obj.f() obj.fn() // window obj obj
3
var n = 10 var obj1={ n:1, f:function(){this.n++; n=this.n++} }
obj1.f() console.log(n) // 2 console.log(obj1.n) // 2 window.setTimeout(obj1.f, 1000)
//2 //3
4
console.log(getA) if('a' in window){ var a = '' function getA(a){ a = a||this.a console.log(this.a) } getA(a) }
5
var a=2 var obj1 = { a:1, fn1: (function(a){ this.a = a a++ return function(){ this.a = a++ console.log(a) }
})(a)
} obj1.fn1() // 4 var fn1 = obj1.fn1 fn1() // window.a = 4,a=5
6
var c=3 function getC(){ this.c++ return function (){ c=this.c*2 console.log(c) } } var obj3={ c: 2, getC:(function(){ this.c -= 1 return this.getC })() } getC() // window.c = 3 obj3.getC() // obj3.c=3 var f3=obj3.getC f3() // window.c=4 console.log(window.c) // 4 console.log(obj3.c) // 3
for (var i = 1; i <= 5; i++) {
setTimeout( function timer() {
console.log(i);
}, 1000 );
}
上面的代码会输出什么?怎么改动上述代码,使其依次输出1、2、3、4、5 并说明原因
理论题: 谈谈什么是闭包