История мальчика, изучающего React — Часть 1
Как мы ошибались насчет классов
Взгляните — класс в формате JSON: Object = {key:value, key:value}
var person = { company: 'alphaa', type: 'x-class', items:[{name:'i1'}, {name:'i2'}, {name:'i3'}, {name:'i4'}], doSomethingWrong:function(){ this.items.forEach(function(x,i){ //prints undefined console.log(this.company + ' ' + x.name); }) }, doSomethingRight:function(){ this.items.forEach (x,i) => { //prints company name console.log(this.company + ' ' + x.name); } } }
Класс как объект:
Объект = новая функция {this.key = значение; this.func=функция(){}}
Область действия this
в стрелочных функциях наследуется от контекста выполнения. Стрелочная функция вообще не связывает this
, поэтому всякий раз, когда вы используете this
в стеке вызовов.
var p = new function () { var ref = this; this.company = 'alphaa'; this.class = 'x-class'; this.items = [ {name:'i1'}, {name:'i2'}, {name:'i3'}, {name:'i4'} ]; //WRONG WAY: this will come as undefined this.doSomething = function(){ this.items.forEach(function(x,i){ //this.company will be undefined because this took the //context of the items loop console.log(this.company + ' ' + x.name); }) }; //WRONG WAY: Using variables to access this this.doSomethingWrong = function(){ this.items.forEach(function(x,i){ //DON'T DO THIS, BUT THIS WORKS : ref.company will work but //not a good practice console.log(ref.company + ' ' + x.name); }); }; //CORRECT WAY: to define functions and use Arrow Functions this.doSomethingRight = privateFunction; function privateFunction(){ //this scope in arrow functions are inherited from the //execution context and an arrow function does not bind this //at all. this.items.forEach ((x,i) => { console.log(this.company + ' ' + x.name); }); }; }