简体   繁体   中英

trying to understand Function.prototype.call in js

<script>
var animals = [
  {species: 'Lion', name: 'King'},
  {species: 'Whale', name: 'Fail'}
];

for (var i = 0; i < animals.length; i++) {
  (function (i) { 
    this.print = function () { 
      console.log('#' + i  + ' ' + this.species + ': ' + this.name); 
    } 
    this.print();
  }).call(animals[i], i);
}

</script>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcall

Question:

1.why write this way: this.print, this.species, this.name? I tried to remove 'this', and in console log shows 'undefined'

2. call(animals[i], i) what is the difference between it and call(this, i) ?

To answer your question in reverse order...

(function()).call(...) sets the context in which the function is to execute. ie it sets the this object to the first argument. In your example the first version sets this to the element in the animals[] array. the second will set the context to whatever this is - here it will be the global context.

Once the context is set, your code can refer to it with the this keyword. In your first question this refers to the current animals[] element, so it can extract the species, name, etc. for each animal. Omitting the this keyword refers to variables in the global scope, which aren't defined.

You have actually created an Anonymous Constructor Function, which is what this is referring to when you made the Anonymous Constructor Function. Using call(animals[i]) changes the context of this to each of the Object Literals inside of your animals Array as they pass through your loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM