Sobes.tech
Junior

როგორ შევცვალოთ ფუნქციის კონტექსტი JavaScript-ში?

sobes.tech AI

პასუხი AI-სგან

JavaScript-те функцияның атқару контексты (this мәні) бірнеше тәсілмен өзгертілуі мүмкін:

  1. call(): Функцияны белгіленген this мәнімен және аргументтерімен, оларды жеке-жеке, үтір арқылы бөлектеп, орындау.

    // function.call(thisArg, arg1, arg2, ...)
    function greet(name) {
      console.log(`Сәлем, ${name}! Мен ${this.type}`);
    }
    
    const obj = { type: 'объект' };
    
    greet.call(obj, 'Алиса'); // Сәлем, Алиса! Мен объект
    
  2. apply(): Функцияны белгіленген this мәнімен және аргументтері массив немесе массив тәрізді объект түрінде беріледі.

    // function.apply(thisArg, [argsArray])
    function sum(a, b) {
      console.log(`${this.name}: ${a + b}`);
    }
    
    const context = { name: 'Калькулятор' };
    const numbers = [5, 10];
    
    sum.apply(context, numbers); // Калькулятор: 15
    
  3. bind(): Жаңа функция құрады, ол белгіленген this мәніне "байланыстырылған". Орындау үшін шақырылмайды.

    // function.bind(thisArg, arg1, arg2, ...)
    const user = { name: 'Боб' };
    
    function sayHello() {
      console.log(`Менің атым ${this.name}`);
    }
    
    const boundSayHello = sayHello.bind(user);
    
    boundSayHello(); // Менің атым Боб
    
  4. Нителдік функциялар (=>): Өзінің this-і жоқ. Олар лексикалық ортадан (this) алады.

    class MyClass {
      constructor() {
        this.value = 'класс мәні';
        // Нителдік функция класс контекстін сақтайды
        this.logValue = () => {
          console.log(this.value);
        };
      }
    }
    
    const instance = new MyClass();
    const method = instance.logValue;
    
    method(); // класс мәні (контекст сақталған)
    
    // Қарапайым функциямен салыстырғанда, bind қолданылмаған
    class AnotherClass {
        constructor() {
            this.value = 'басқа мән';
            this.logValue = function() {
                console.log(this.value); // 'this' болады window немесе strict режимде undefined
            };
        }
    }
    
    const anotherInstance = new AnotherClass();
    const anotherMethod = anotherInstance.logValue;
    
    anotherMethod(); // undefined (контекст жоғалды)