Sobes.tech
Junior

Ako zmeniť kontext funkcie v JavaScripte?

sobes.tech AI

Odpoveď od AI

V JavaScripte je kontekst izvršavanja funkcije (vrednost this) moguće promeniti na više načina:

  1. call(): Izvršava funkciju sa zadatom vrednošću this i argumentima koji se prosleđuju pojedinačno, odvojeni zarezom.

    // function.call(thisArg, arg1, arg2, ...)
    function greet(name) {
      console.log(`Ahoj, ${name}! Ja som ${this.type}`);
    }
    
    const obj = { type: 'objekt' };
    
    greet.call(obj, 'Alena'); // Ahoj, Alena! Ja som objekt
    
  2. apply(): Izvršava funkciju sa zadatom vrednošću this i argumentima prosleđenim u obliku niza ili sličnog niza.

    // function.apply(thisArg, [argsArray])
    function sum(a, b) {
      console.log(`${this.name}: ${a + b}`);
    }
    
    const context = { name: 'Kalkulator' };
    const numbers = [5, 10];
    
    sum.apply(context, numbers); // Kalkulator: 15
    
  3. bind(): Kreira novu funkciju, "privezanu" za zadatu vrednost this. Originalna funkcija se ne izvršava odmah.

    // function.bind(thisArg, arg1, arg2, ...)
    const user = { name: 'Bob' };
    
    function sayHello() {
      console.log(`Moje ime je ${this.name}`);
    }
    
    const boundSayHello = sayHello.bind(user);
    
    boundSayHello(); // Moje ime je Bob
    
  4. Streličaste funkcije (=>): Streličaste funkcije nemaju svoj vlastiti this. Oni zarobljavaju this iz leksičkog okruženja (iz običnog roditeljskog scope-a gde su definisane).

    class MyClass {
      constructor() {
        this.value = 'vrednost klase';
        // Strelička funkcija zadržava kontekst klase
        this.logValue = () => {
          console.log(this.value);
        };
      }
    }
    
    const instance = new MyClass();
    const method = instance.logValue;
    
    method(); // vrednost klase (kontekst sačuvan)
    
    // Uporedite sa običnom funkcijom bez bind
    class AnotherClass {
        constructor() {
            this.value = 'druga vrednost';
            this.logValue = function() {
                console.log(this.value); // 'this' će biti window ili undefined u strogo režimu
            };
        }
    }
    
    const anotherInstance = new AnotherClass();
    const anotherMethod = anotherInstance.logValue;
    
    anotherMethod(); // undefined (kontekst izgubljen pri pozivu kao odvojena funkcija)