javascript - What is happening when using the keyword this in lambdas vs functions with Typescript -
this question has answer here:
i using typescript angular 2 project. notice when use keyword this
inside labmda expression vs function, this
refers different things.
for example, let's have angular component following.
export class mycomponet { isactive = true; names = [ "john", "jeff", "jared" ]; dosomethingwithlambda() { names.foreach( (value, index) => { if(this.isactive) { //this.isactive refers mycomponent.isactive //do something... } }); } dosomethingwithfunction() { names.foreach( function(value, index) { if(this.isactive) { //this.isactive undefined, since refers function //do } }); } dosomethingwithfunction2() { let isactive = this.isactive; names.foreach( function(value, index) { if(isactive) { //if change isactive change mycomponent.isactive? //do } }); } }
what happening here (behind scene, speak)? what's magic behind this
inside lambda makes able "correctly" refer outer class' fields? understand this
inside function refer function itself.
also, have dosomethingwithfunction2
method reference mycomponent.isactive
local variable. if change local variable, should changing 1 references, right? (regardless of being "primitive" integer/number or "object" json { })
the fat-arrow function syntax shorthand for:
function () { }.bind(this);
bind
javascript es5 method equivalent this:
function.prototype.bind = function bind(context) { var func = this; return function () { return func.apply(context, arguments); }; }
in regards
also, have dosomethingwithfunction2 method reference mycomponent.isactive local variable. if change local variable, should changing 1 references, right? (regardless of being "primitive" integer/number or "object" json { })
in javascript, variables pointers , except limited cases (primitives , copy-on-write objects) change referenced value when mutated. reassigning not change original value, e.g. isactive = false;
this.isactive = false
in fact re-assign variable isactive
on this
correctly assigned.
Comments
Post a Comment