@yvetrov

Зачем thisArg в прокси-объекте JS?

Зачем нужен thisArg в прокси-объекте? Если мы проверим данное утверждение:

let target = function () { console.log('I am the target'); };
let handler = {
    apply: function (target, thisArg, args) {
        console.log(`Целевой объект: ${target}, значение this: ${thisArg}, список аргументов: ${args}`);
        thisArg === target ? console.log('this') : console.log('not this');
        return 'I am the proxy';
    }
};

let p = new Proxy(target, handler);
console.log(target(1));
console.log(p(1));


А именно:
thisArg === target ? console.log('this') : console.log('not this');


То получим not this. Тогда зачем вообще нужен параметр thisArg?
  • Вопрос задан
  • 171 просмотр
Решения вопроса 1
@FabiBoom
Сдесь он нужен, чтобы определить в каком контексте вызван handler:

let handler = {
    apply: function (target, thisArg, args) {
        console.log(`this=${thisArg}`); // obj
        console.log(thisArg === obj); // true
        console.log(this); // Proxy
    }
};

let obj = {
  p: new Proxy(target, handler)
};

obj.p(1, 2);


apply parameters
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы