You do not know the JS series (18) - erroneous understanding of this

The first misunderstanding: this function is understood to point to the province, as a function of the object, this is not as we thought it would point to the function itself.

 

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.



The second misunderstanding: this points to a function's scope. In some cases it is true, but it is clear, this is not directed in any case lexical scope of the function.

 

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.

 

The first step of this study is to understand this point neither the function itself does not point to the lexical scope of a function.

 

this is bound at runtime, not binding when writing. Location binding and function declarations this has nothing to do, depends only on the function is called.







Guess you like

Origin www.cnblogs.com/wzndkj/p/12400209.html