How to use this

How to use this

$this keyword in PHP

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.

Example 1: A simple program to show the use of $this in PHP.

Output:

$this – a pseudo-variable: Unlike other reserved keywords used in the context of class like the static, parent, etc does not need to be declared with the dollar sign (‘$’). This is because in PHP $this is treated as a pseudo-variable.
In PHP, this is declared like a variable declaration (with the ‘$’ sign) even though it is a reserved keyword. More specifically, $this is a special read-only variable that is not declared anywhere in the code and which represents a value that changes depending on the context of program execution.

Example 2: A program that updates the value of a variable of a specific object using $this keyword.

Output:

As of PHP 7.0.0, calling a non-static method statically from an incompatible context results in $this being “undefined” to the method. Calling a non-static method statically from an incompatible context has been deprecated as of PHP 5.6.0. As of PHP 7.0.0 calling a non-static method statically has been deprecated (even if called from a compatible context). Before PHP 5.6.0, such calls already triggered a strict notice.

Example 3: In this example, $this keyword becomes “not defined” when a non-static method is called in the context of a static one.

this Keyword in Java: What is & How to use with Example

Updated June 11, 2022

What is this Keyword in Java?

this keyword in Java is a reference variable that refers to the current object of a method or a constructor. The main purpose of using this keyword in Java is to remove the confusion between class attributes and parameters that have same names.

Following are various uses of ‘this’ keyword in Java:

Click here if the video is not accessible

Understand ‘this’ keyword with an example.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use thisJava this keyword Example

Let’s compile and run the code

Our expected output for A and B should be initialized to the values 2 and 3 respectively.

But the value is 0, Why? Let investigate.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

In the method Set data, the arguments are declared as a and b, while the instance variables are also named as a and b.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

During execution, the compiler is confused. Whether “a” on the left side of the assigned operator is the instance variable or the local variable. Hence, it does not set the value of ‘a’ when the method set data is called.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

The solution is the “this” keyword

Append both ‘a’ and ‘b’ with the Java this keyword followed by a dot (.) operator.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

During code execution when an object calls the method ‘setdata’. The keyword ‘this’ is replaced by the object handler “obj.” (See the image below).

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

So now the compiler knows,

The variables are initialized correctly, and the expected output is shown.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

Suppose you are smart enough to choose different names for your instance variable and methods arguments.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

But this time around, you create two objects of the class, each calling the set data method.

How the compiler will determine whether it is supposed to work on instance variable of object 1 or object 2.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

Well, the compiler implicitly appends the instance variable with “this” keyword (image below).

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

Such that when object 1 is calling the set data method, an instance variable is appended by its reference variable.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

While object 2 is calling the set data method, an instance variable of object 2 is modified.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

This process is taken care by the compiler itself. You don’t have to append ‘this’ keyword explicitly unless there is an exceptional situation as in our example.

Example: To learn the use “this” keyword

Step 1) Copy the following code into a notepad.

Step 3) Value of a & b is shown as zero? To correct the error append line # 6 & 7 with “this” keyword.

Step 4) Save, Compile, and Run the code. This time around, values of a & b are set to 2 & 3 respectively.

Summary

Check our article on Java Interview Questions:- Click here

How to use this

A function’s this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

In most cases, the value of this is determined by how a function is called (runtime binding). It can’t be set by assignment during execution, and it may be different each time the function is called. The bind() method can set the value of a function’s this regardless of how it’s called, and arrow functions don’t provide their own this binding (it retains the this value of the enclosing lexical context).

Try it

Syntax

Value

A property of an execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.

Description

Global context

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

Note: You can always easily get the global object using the global globalThis property, regardless of the current context in which your code is running.

Function context

Inside a function, the value of this depends on how the function is called.

Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser.

Class context

The behavior of this in classes and functions is similar, since classes are functions under the hood. But there are some differences and caveats.

Within a class constructor, this is a regular object. All non-static methods within the class are added to the prototype of this :

Derived classes

Unlike base class constructors, derived constructors have no initial this binding. Calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where Base is the inherited class:

Warning: Referring to this before calling super() will throw an error.

Examples

this in function contexts

this and object conversion

The bind() method

Arrow functions

No matter what, foo ‘s this is set to what it was when it was created (in the example above, the global object). The same applies to arrow functions created inside other functions: their this remains that of the enclosing lexical context.

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

this on the object’s prototype chain

The same notion holds true for methods defined somewhere on the object’s prototype chain. If the method is on an object’s prototype chain, this refers to the object the method was called on, as if the method were on the object.

this with a getter or setter

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

As a constructor

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

In the last example ( C2 ), because an object was returned during construction, the new object that this was bound to gets discarded. (This essentially makes the statement this.a = 37; dead code. It’s not exactly dead because it gets executed, but it can be eliminated with no outside effects.)

As a DOM event handler

When a function is used as an event handler, its this is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener() ).

In an inline event handler

When the code is called from an inline on-event handler, its this is set to the DOM element on which the listener is placed:

In this case, the inner function’s this isn’t set so it returns the global/window object (i.e. the default object in non–strict mode where this isn’t set by the call).

this in classes

Just like with regular functions, the value of this within methods depends on how they are called. Sometimes it is useful to override this behavior so that this within classes always refers to the class instance. To achieve this, bind the class methods in the constructor:

Note: Classes are always strict mode code. Calling methods with an undefined this will throw an error.

How To Use Javascript Arrow Functions & This Keyword

January 19, 2021

ES6 introduced a new way of writing JavaScript functions called arrow function that uses a fat arrow ( => ).

This guide will discuss how to use the arrow function to write your JavaScript functions. Focusing on converting regular functions to arrow functions as we consider when not to use arrow functions. To understand the arrow functions, it is essential to have prior knowledge of JavaScript functions.

What are the arrow functions

It is a sort of an abbreviated way to write compact functions.

The following are a few facts about arrow functions:

One of the main differences between arrow functions and regular functions is that arrow functions can only be anonymous. They are not bound to any identifier.

Thus they created dynamically. We cannot name an arrow function as we do for the regular functions. However, if you’d like to call or reuse an arrow function, you will need to assign it to a variable.

Arrow functions are always anonymous.

To call an arrow function and reuse it, you need to store it in a variable, for example:

How to use arrow functions

One aspect you will recognize frequently is the range of syntaxes usable in the arrow functions. Arrow function have a lot of variations and different syntax depending on your block of code.

Let’s discuss some of the common ones.

Here is a standard arrow function syntax.

Arrow functions are denoted with the following syntax:

When writing an arrow function:

More dynamic arrow functions syntax

Let’s try to derive more arrow function syntaxes by converting some regular functions to arrow functions.

Example one: A function with one argument.

Wow, note the difference. The results will be the same, the code gets smaller and more compact, with an arrow function, we arrive at one line of code, and the code’s logic remains the same.

From the above examples, passing one parameter can derive a summary of the following syntax.

If the function body has more than one statement, you need to wrap the function body with the curly brackets and use the return keyword to return the results.

Example two: A function with multiple parameters.

Curly brackets are optional, and since we have one statement, we can do away with the return keyword.

Because we have more than one parameter, you need to wrap the parameters with parentheses ( (x,y) ). Otherwise, that will be a syntax error.

We can derive the following syntax.

Because more than one parameter requires parentheses, rest and destructing parameters can be implemented using an arrow function.

They both need parentheses.

Example three: A function with an anonymous function.

It is a function with no name.

Here is an example.

Example four: Anonymous Function with Parameters.

This is how we can replicate the example above using the arrow function.

A clear note here is that the anonymous function always uses the parentheses.

Syntax summary.

Anonymous functions are mostly applied as an argument to another function. Such as a callback.

In this case, the anonymous function is passed as an argument to the setTimeout() function. After 3 seconds, the anonymous function will be executed.

This is how we can write the above anonymous function using the arrow function.

Some common applications of arrow functions

Arrow functions and callbacks

The arrow function syntax is heavily seen when using callback functions.

Assume you have an array of donors:

This is how we can apply filter and map using the regular function syntax:

Replicate the logic above using an arrow function.

The arrow function makes the callback function compact and less verbose. This doesn’t affect the readable code.

Arrow function and this context

this represents an object that executes the current function. In short, this is defined by the function execution context. Such as how a function is called, it refers to a global object window. For example, when a function is being executed from a global object.

You might have used this keyword in a real-life situation without realizing it. Suppose you are walking along with your mother and meet a friend along the way. This is how you would introduce your mom to your friend. This is my mother.

Take a close look at this is that sentence. this shows a reference to your mother. this represents the mother in the current sentence. It is the same way JavaScript uses this keyword.

Log This is my mother to the console. But what if we replace “this” in the sentence with JavaScript this keyword.

If we specify the mother’s name.

Samantha Quinn is my mother, will be printed in the console.

What if we use this globally. Let’s see that with examples.

Run the above call in a browse console. You will get something like:

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

This is because the test() is called from a global context, and this will refer to a global object. In this case, a global object window is called from the browser. this is not defined by the caller.

Thus, it will turn to the default window object. The Javascript engine will check if test() is available in the window object. If not, the engine will add it to the many available Javascript window object methods.

Let’s get a little complex. What if we use the arrow function.

this in regular function always refers to the context of the function being called. However, in the arrow function, this has nothing to do with the caller of the function. It refers to the scope where the function (the enclosing context) is present. That’s why we get undefined.

However, when the innerFunction is inside an arrow function, this will refer to the parent scope by creating this of its own context.

Let’s look at the broader scope of how the arrow function binds to this keyword.

Here is an example that uses the regular function.

Execute the examples below with the console. You can use the Google chrome console.

The above example accesses the object’s property domesticAnimals and prints the domestic animals in 3 seconds. Unfortunately, we ran into an error.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

Does it refer to the:

The example below will help us to understand where this keyword points. We will log this inside the context of outer ( printdomesticAnimals() ) and inner ( setTimeout() ) function.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

this inside printdomesticAnimals() points to the object animals with the domesticAnimals property. this inside setTimeout() points to the window object where property domesticAnimals is undefined.

This is where the arrow function comes into play. They don’t have their own this context. When used inside the outer (enclosing) function, this keyword will point to where the function is present.

In this case, this will be attached to the outer context printdomesticAnimals() where setTimeout() is called. printdomesticAnimals() will be the enclosing context where this will be attached.

When we use the arrow function, we get the results as we expected.

How to use this. Смотреть фото How to use this. Смотреть картинку How to use this. Картинка про How to use this. Фото How to use this

Arrow functions with object literal

Let’s have an example that represents a JavaScript object.

sayName() is a function expression that returns an object that has properties name and age set to “John Doe” and “26”, respectively.

Convert to an arrow function.

You should note that when we return the literal object using the arrow function it causes an error. This is because JavaScript can’t distinguish if the curly braces represent a block of code or an object.

To solve this, wrap the literal object with parenthesis.

When not to use arrow functions

The arrow functions concept is great, however, they are not ideal across all functional instances. You should be keen on where to apply the arrow function.

For example, there are some instances that you should avoid using.

Arrow function can never be a method

For example, this applies to the mom example we explained earlier

In this case, this.mom_name return undefined because this value is equal to the method upon where we call the object property.

As we said earlier, this inside an arrow function is equivalent to the global object.

Whenever an arrow function is inside an object, it will derive this value from the enclosing lexical scope. Lexical scope, in this case, is the global scope.

this.mom_name in the mother method is equal to the window.mom_name in the web browser. The window.mom_name is undefined by default.

To prevent the this value from binding to the global scope, use the regular function inside the object method as follows:

Avoid arrow functions when using a code block with methods. They can be confusing at times due to their lexical scoping. This occurs mostly on object methods, prototype methods, and class methods. this is scoped to the parent (window) context.

An arrow function can never be a constructor

When you execute, this will throw an error Uncaught TypeError: User is not a constructor because arrow functions are not constructable.

Using the new keyword to create an object in an arrow function will output an error.

Click handlers

Here is the code to implement a click me button.

When you click the button, you get an error. But why? This means that this in the click event handle is undefined. And will always return undefined.

Debugging may not be easy

Arrow functions cannot be named. They are anonymous. Anonymous functions are labeled as anonymous during a debugging session.

This doesn’t give you any idea what the code block is running. When you run into issues, it may be harder to debug the root cause. When the functions have names, it’s simpler to trace back to the problem. With anonymous functions, it adds a level of complexity to debugging.

Readability takes a hit

Although arrow functions help with writing short and concise code, it is not necessarily readable. Most programmers are used to the traditional way of writing functions, and arrow functions change this completely. This makes code harder to read and might take a while for someone newer to grasp the code.

Therefore in such circumstances, developers may choose to use regular functions rather than arrow functions. The primary objective when you compose a function is to create the purest function practicable. Meaning that the function would still return its same value. If you’re using regular functions or arrow functions, it doesn’t matter. It should be about writing readable and cleaner code always.

Final Notes

Arrow functions save you some keystrokes when working with the functions. They are especially useful for inline functions, as they pass along the outer this context.

With an arrow function:

As a beginner, arrow functions seem unfamiliar and hard to read. They take time to understand. As you learn about them, they become convenient and straightforward to implement in your functions.

I hope this guide gives you an overview of applying the fat arrow within your functional code blocks.

Peer Review Contributions by: Adrian Murage

Перевод «Know how to use this» на русский

знаешь, как этим пользоваться
znayesh’, kak etim pol’zovat’sya

5 примеров, содержащих перевод

знать, как использовать эту
znat’, kak ispol’zovat’ etu

3 примеров, содержащих перевод

знают, как использовать эту
znayut, kak ispol’zovat’ etu

3 примеров, содержащих перевод

знаю, как этим пользоваться
znayu, kak etim pol’zovat’sya

3 примеров, содержащих перевод

знаете, как использовать эту
znayete, kak ispol’zovat’ etu

3 примеров, содержащих перевод

знаете, как использовать это
znayete, kak ispol’zovat’ eto

2 примеров, содержащих перевод

знаешь, как пользоваться этой
znayesh’, kak pol’zovat’sya etoy

2 примеров, содержащих перевод

знают, как использовать это
znayut, kak ispol’zovat’ eto

2 примеров, содержащих перевод

умеешь этим пользоваться
umeyesh’ etim pol’zovat’sya

2 примеров, содержащих перевод

знаешь как этим пользоваться
znayesh’ kak etim pol’zovat’sya

2 примеров, содержащих перевод

знаете, как этим пользоваться
znayete, kak etim pol’zovat’sya

2 примеров, содержащих перевод

знают, как использовать этот
znayut, kak ispol’zovat’ etot

2 примеров, содержащих перевод

знаю, как пользоваться этим
znayu, kak pol’zovat’sya etim

2 примеров, содержащих перевод

умеете этим пользоваться
umeyete etim pol’zovat’sya

2 примеров, содержащих перевод

знаете, как пользоваться этой
znayete, kak pol’zovat’sya etoy

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *