4 вида путаницы с this в функциях

Sean, “4 Ways Functions Mess With this”, public translation into Russian from English More about this translation.

Translate into another language.

Participants

Fenrir865 points
m_vokhm488 points
kron0s475 points
And others...
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next
1 2 3 4

4 Ways Functions Mess With this

4 вида путаницы с this в функциях

History of edits (Latest: Fenrir 2 years, 1 month ago) §

In Javascript, the this keyword can be a tricky thing. It's trickiness comes from how functions behave differently depending on how you call them. What? You can call them differently? Yep! There's 4 major invocation patterns for a function, so let's see how each works, and how they handle this.

В JavaScript ключевое слово this может быть очень коварно. Эта происходит из-за разного поведения функций в зависимости от способа их вызова. Что? Функции можно вызывать по-разному? Ага! Есть 4 основных способа вызова функций. Посмотрим, как работает каждый, и как они обходятся с this.

History of edits (Latest: kron0s 2 years ago) §

— У меня был огромный соблазн перевести "trickiness" как "подстава". Но адекватный литературный вариант так и не нашелся. Fenrir

— "this может быть очень коварно" тоже не совсем литературно звучит kron0s

1. Method Invocation

1. Вызов метода

History of edits (Latest: Fenrir 2 years, 1 month ago) §

2. Function Invocation

2. Вызов функции

History of edits (Latest: Fenrir 2 years, 1 month ago) §

3. Constructor Invocation

3. Вызов конструктора

History of edits (Latest: Fenrir 2 years, 1 month ago) §

4. Apply Invocation

4. Вызов через apply

History of edits (Latest: Fenrir 2 years, 1 month ago) §

Method Invocation

Вызов метода

History of edits (Latest: Fenrir 2 years, 1 month ago) §

The first patten of using functions will look the most familiar. When you come from classical programming languages (C#, Java), you're likely used to classes being the only building blocks of a program. Nothing can exist without a class. You only have a function that is a method of a class. And it's super simple what this relates to.

Первый способ использования функций выглядит наиболее привычно. При переходе с классического языка программирования (C#, Java) вы наверняка привыкли использовать классы как единственные строительные блоки программы. Ничто не может существовать вне класса. У вас есть функции только как методы классов. И абсолютно ясно, к чему относится this.

History of edits (Latest: Fenrir 2 years, 1 month ago) §

Well, that is the same way method invocation works in Javascript. If you define an Object, and make one of its properties a function, then when you execute that method, this will be the Object that owns it.

Отлично, таким же образом работает вывоз метода в JavaScript. Если вы определите объект Object, и сделаете одно из его свойств функцией, затем вызовете этот метод, тогда this будет объектом Object, к которому принадлежит эта функция.

History of edits (Latest: Fenrir 2 years, 1 month ago) §

var Obj = {

var Obj = {

History of edits (Latest: kron0s 2 years, 2 months ago) §

something: 'a string',

something: 'строка',

History of edits (Latest: Fenrir 2 years, 1 month ago) §

changeSomething: function() {

changeSomething: function() {

History of edits (Latest: Fenrir 2 years, 1 month ago) §

//this == Obj

//this == Obj

History of edits (Latest: Fenrir 2 years, 1 month ago) §

return this.something.toUpperCase();

return this.something.toUpperCase();

History of edits (Latest: Fenrir 2 years, 1 month ago) §

}

}

History of edits (Latest: Fenrir 2 years, 1 month ago) §

};

};

History of edits (Latest: Fenrir 2 years, 1 month ago) §

Obj.changeSomething(); //returns 'A STRING'

Obj.changeSomething(); //вернёт 'СТРОКА'

History of edits (Latest: Fenrir 2 years, 1 month ago) §

var Obj = {

var Obj = {

History of edits (Latest: Fenrir 2 years, 1 month ago) §

something: 'a string',

something: 'строка',

History of edits (Latest: Fenrir 2 years, 1 month ago) §

changeSomething: function() {

changeSomething: function() {

History of edits (Latest: Fenrir 2 years, 1 month ago) §

//this == Obj

//this == Obj

History of edits (Latest: Fenrir 2 years, 1 month ago) §

return this.something.toUpperCase();

return this.something.toUpperCase();

History of edits (Latest: Fenrir 2 years, 1 month ago) §

}

}

History of edits (Latest: Fenrir 2 years, 1 month ago) §

};

};

History of edits (Latest: Fenrir 2 years, 1 month ago) §

Obj.changeSomething(); //returns 'A STRING'

Obj.changeSomething(); //вернёт 'СТРОКА'

History of edits (Latest: Fenrir 2 years, 1 month ago) §

Anytime we call changeSomething of Obj, like above, we know this will be Obj, so we don't have to repeat the name of the object constantly. This is also the same if we were to clone the object. this would reference the object that owns the method.

Когда бы мы ни вызвали changeSomething объекта Obj таким способом, мы знаем, что это будет Obj, и нет необходимости постоянно повторять название объекта. Это также будет верно, если мы клонируем объект. this будет указывать на объект, владеющий методом.

History of edits (Latest: kron0s 2 years ago) §

Function Invocation

Вызов функции

History of edits (Latest: Fenrir 2 years, 1 month ago) §

The second pattern, might look a little stranger, and seem to behave strange also, but once you realize a few things about Javascript, you'll see there is logic behind it (yes, really!). The next pattern is commonly called the Function invocation, and this is basically where we define a function all by its lonesome self. This is possible because in Javascript, functions are first-class objects. So they can be passed around, stored, all the good stuff. But let's assume we know all this.

Второй способ может выглядеть немного странно, и его поведение также может показаться странным, но, как только вы лучше поймете особенности JavaScript, вы увидите логику такого поведения (точно-точно!). Следующий способ обычно называется «вызов функции», он заключается в определении функции самой по себе, а не как метода класса. В JavaScript это возможно, поскольку функции являются объектами первого рода. Их можно передавать как аргументы, сохранять в переменных, и делать прочие классные вещи. Предположим, что мы всё это знаем.

History of edits (Latest: Fenrir 2 years, 1 month ago) §

— Автор текста - явный джаваист или что-то похожее. У них нельзя задать "просто функцию". Там нет вообще понятия функции, есть только классы. Потому он и обозвал это как "задать одинокую функцию саму по себе". Тут не имелось в виду, что это какой-то самодостаточный кусок, а только то, что она не входит ни в какой класс. Fenrir

Pages: ← previous Ctrl next
1 2 3 4