Telegram Group & Telegram Channel
В чем различие методов call apply bind?

Методы call, apply и bind принадлежат к функциональному объекту Function и используются для указания контекста this при вызове функции. Хотя все три метода позволяют контролировать значение this внутри функции, между ними существуют ключевые различия в способе использования и поведении.

Сall
Вызывает функцию, явно устанавливая this в первом аргументе. Остальные аргументы передаются в вызываемую функцию как есть.

Пример:
function greet(message, name) {
console.log(${message}, ${name}. This is ${this});
}

greet.call("Earth", "Hello", "Alice"); // "Hello, Alice. This is Earth"



Здесь он используется для вызова функции greet с this, установленным в "Earth", и двумя дополнительными аргументами "Hello" и "Alice".

Apply

Очень похож на call, но принимает аргументы в виде массива, а не по отдельности.

Пример:
function greet(message, name) {
console.log(
${message}, ${name}. This is ${this}
);
}

greet.apply("Earth", ["Hello", "Alice"]); // "Hello, Alice. This is Earth"



В этом случае он вызывает функцию greet с this, установленным в "Earth", и аргументами, переданными в виде массива.

Bind

Создаёт новую функцию, которая, когда она вызывается, имеет установленный контекст this, указанный в первом аргументе. В отличие от call и apply, bind не вызывает функцию сразу, а возвращает новую функцию, которую можно вызвать позже.

Пример:
function greet(message, name) {
console.log(
${message}, ${name}. This is ${this}
);
}

const greetEarth = greet.bind("Earth", "Hello", "Alice");
greetEarth(); // "Hello, Alice. This is Earth"


Здесь он используется для создания новой функции greetEarth, которая при вызове выводит тот же результат, что и предыдущие примеры, но с тем отличием, что контекст this и аргументы были заранее заданы.

👉 @frontendInterview



tg-me.com/frontendInterview/4694
Create:
Last Update:

В чем различие методов call apply bind?

Методы call, apply и bind принадлежат к функциональному объекту Function и используются для указания контекста this при вызове функции. Хотя все три метода позволяют контролировать значение this внутри функции, между ними существуют ключевые различия в способе использования и поведении.

Сall
Вызывает функцию, явно устанавливая this в первом аргументе. Остальные аргументы передаются в вызываемую функцию как есть.

Пример:

function greet(message, name) {
console.log(${message}, ${name}. This is ${this});
}

greet.call("Earth", "Hello", "Alice"); // "Hello, Alice. This is Earth"



Здесь он используется для вызова функции greet с this, установленным в "Earth", и двумя дополнительными аргументами "Hello" и "Alice".

Apply

Очень похож на call, но принимает аргументы в виде массива, а не по отдельности.

Пример:
function greet(message, name) {
console.log(
${message}, ${name}. This is ${this}
);
}

greet.apply("Earth", ["Hello", "Alice"]); // "Hello, Alice. This is Earth"



В этом случае он вызывает функцию greet с this, установленным в "Earth", и аргументами, переданными в виде массива.

Bind

Создаёт новую функцию, которая, когда она вызывается, имеет установленный контекст this, указанный в первом аргументе. В отличие от call и apply, bind не вызывает функцию сразу, а возвращает новую функцию, которую можно вызвать позже.

Пример:
function greet(message, name) {
console.log(
${message}, ${name}. This is ${this}
);
}

const greetEarth = greet.bind("Earth", "Hello", "Alice");
greetEarth(); // "Hello, Alice. This is Earth"


Здесь он используется для создания новой функции greetEarth, которая при вызове выводит тот же результат, что и предыдущие примеры, но с тем отличием, что контекст this и аргументы были заранее заданы.

👉 @frontendInterview

BY Frontend Interview - собеседования по Javascript / Html / Css




Share with your friend now:
tg-me.com/frontendInterview/4694

View MORE
Open in Telegram


Frontend Interview собеседования по Javascript Html Css Telegram | DID YOU KNOW?

Date: |

At a time when the Indian stock market is peaking and has rallied immensely compared to global markets, there are companies that have not performed in the last 10 years. These are definitely a minor portion of the market considering there are hundreds of stocks that have turned multibagger since 2020. What went wrong with these stocks? Reasons vary from corporate governance, sectoral weakness, company specific and so on. But the more important question is, are these stocks worth buying?

Telegram Gives Up On Crypto Blockchain Project

Durov said on his Telegram channel today that the two and a half year blockchain and crypto project has been put to sleep. Ironically, after leaving Russia because the government wanted his encryption keys to his social media firm, Durov’s cryptocurrency idea lost steam because of a U.S. court. “The technology we created allowed for an open, free, decentralized exchange of value and ideas. TON had the potential to revolutionize how people store and transfer funds and information,” he wrote on his channel. “Unfortunately, a U.S. court stopped TON from happening.”

Frontend Interview собеседования по Javascript Html Css from us


Telegram Frontend Interview - собеседования по Javascript / Html / Css
FROM USA