[ Web Proxy ]
URL:
Viewing: https://ar.javascript.info/reference-type [Back]  [Original]

:
Light themeDark theme
DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek

, .

. . .

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:

  1. , '.' obj.method.
  2. () .

, 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 .
  • strict use 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.

: 2

?

let user = {
  name: "John",
  go: function() { alert(this.name) }
}

(user.go)()

. :)

!

:

let user = {
  name: "John",
  go: function() { alert(this.name) }
}

(user.go)() // !

.

user = {...}.

()(user.go), :

let user = { go:... }(user.go)()

{ go: ... } (user.go). let user, user .

:

let user = {
  name: "John",
  go: function() { alert(this.name) }
};

(user.go)() // John

(user.go) . . , . .

: 3

obj.go() 4 .

(1) (2) (3) 4 (4). ?

let obj, method;

obj = {
  go: function() { alert(this); }
};

obj.go();               // (1) [object Object]

(obj.go)();             // (2) [object Object]

(method = obj.go)();    // (3) undefined

(obj.go || obj.stop)(); // (4) undefined

.

  1. .

  2. .

  3. Here we have a more complex call (expression)(). The call works as if it were split into two lines:

    f = obj.go; //  
    f(); //   

    f() , this.

  4. The similar thing as (3), to the left of the parentheses () we have an expression.

(3) (4) ( ) .

( = or ||) this.


Web Proxy Viewer  |  New URL  |  Original Page