1.4 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)
2
function f(){console.log(this)}
var obj={ fn: (function(){ return this.f })(), f: function(){console.log(this)} } f() obj.f() obj.fn()
3
var n = 10 var obj1={ n:1, f:function(){this.n++; n=this.n++} }
obj1.f() console.log(n) console.log(obj1.n) window.setTimeout(obj1.f, 1000)
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() 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() obj3.getC() var f3=obj3.getC f3() console.log(window.c) console.log(obj3.c)
for (var i = 1; i <= 5; i++) {
setTimeout( function timer() {
console.log(i);
}, 1000 );
}
上面的代码会输出什么?怎么改动上述代码,使其依次输出1、2、3、4、5 并说明原因
理论题: 谈谈什么是闭包