function foo(num){ console.log('foo: ' + num); this.count++; } foo.count = 0; var i; for(i=0; i<10; i++){ if (i > 5) { foo(i); } } console.log(foo.count); // 0
foo indeed been called four times, but still foo.count 0. Clearly from the literal meaning to understand this is wrong. If I count property increased and expectations are not the same, then the increase is what count? In fact, if the in-depth exploration, you will find this code creates a global variable inadvertently, its value is NaN. How do we solve this problem?
function foo(num){ console.log('foo: ' + num); // 记录 foo 被调用的次数 data.count++; } var data = { count: 0 } var i; for(i=0; i<10; i++){ if (i > 5) { foo(i); } } console.log(data.count); // 4
In some ways, this approach does solve the problem, but unfortunately it ignores the real problem - and can not understand the meaning of this works - but returns comfort zone, to use a more familiar technology, lexical area
function foo(num){ console.log('foo: ' + num); // 记录 foo 被调用的次数 foo.count++; } foo.count = 0; var i; for(i=0; i<10; i++){ if (i > 5) { foo(i); } } console.log(foo.count); // 4
However, this method also avoids this problem, and depends on the variable foo lexical scoping
function foo(num){ console.log('foo: ' + num); this.count++; } foo.count = 0; var i; for(i=0; i<10; i++){ if (i > 5) { foo.call(foo, i); } } console.log(foo.count); // 4
This time we accepted this, not avoid it.
function foo() { var a = 2; this.bar(); } function bar(){ console.log(this.a); } foo(); // undefined
This code is very perfect show how misleading this person. First this.bar () to reference the bar () function. It is absolutely impossible to succeed. Call bar () this is the most natural way to the front end thereof is omitted. In addition, developers are trying to use this Unicom foo () and bar () lexical scope. Whenever you want to find this and lexical scope of mixed use, be sure to remind myself that this can not be achieved.