, .
. . .
this.
:
let user = {
name: "John",
hi() { alert(this.name); },
bye() { alert("Bye"); }
};
user.hi(); //
// user.hi user.bye
(user.name == "John" ? user.hi : user.bye)(); // Error!
user.hi user.bye. user.hi.
(). !
, , "this" undefined.
( ):
user.hi();
:
(user.name == 'John' ? user.hi : user.bye)(); // !
, ()obj.method.
, ()obj.method:
- ,
'.'obj.method. -
().
, this ?
, this :
let user = {
name: "John",
hi() { alert(this.name); }
}
//
let hi = user.hi;
hi(); // , this
hi = user.hi , , this.
()user.hi , '.' , Reference Type.
. , .
(base, name, strict), :
base.name.strictuse strict.
user.hi , . user.hi :
//
user, 'hi', true;
() , , this (=user ).
, . ().
hi = user.hi , user.hi () . this.
So, as the result, the value of this is only passed the right way if the function is called directly using a dot obj.method() or square brackets obj['method']() syntax (they do the same here). There are various ways to solve this problem such as func.bind().
.
. obj.method() , .
() this .
( ).
The whole mechanics is hidden from our eyes. It only matters in subtle cases, such as when a method is obtained dynamically from the object, using an expression.
<code><pre>10 (plnkr, JSBin, codepen)