Ссылка указатель в javascript

Ссылочный тип

Эта статья охватывает продвинутую тему, чтобы лучше понять некоторые нестандартные случаи.

Она несильно важна. Многие опытные разработчики прекрасно живут, даже не подозревая об этом. Читайте дальше, если хотите узнать, как все работает под капотом.

Некоторые хитрые способы вызова метода приводят к потере значения this , например:

let user = < name: "Джон", hi() < alert(this.name); >, bye() < alert("Пока"); >>; user.hi(); // Джон (простой вызов метода работает хорошо) // теперь давайте попробуем вызывать user.hi или user.bye // в зависимости от имени пользователя user.name (user.name == "Джон" ? user.hi : user.bye)(); // Ошибка!

В последней строчке кода используется условный оператор ? , который определяет, какой будет вызван метод ( user.hi или user.bye ) в зависимости от выполнения условия. В данном случае будет выбран user.hi .

Затем метод тут же вызывается с помощью скобок () . Но вызов не работает как положено!

Вы можете видеть, что при вызове будет ошибка, потому что значением «this» внутри функции становится undefined (полагаем, что у нас строгий режим).

Так работает (доступ к методу объекта через точку):

Так уже не работает (вызываемый метод вычисляется):

(user.name == "John" ? user.hi : user.bye)(); // Ошибка!

Почему? Если мы хотим понять, почему так происходит, давайте разберёмся (заглянем под капот), как работает вызов методов ( obj.method() ).

Ссылочный тип: объяснение

Присмотревшись поближе, в выражении obj.method() можно заметить две операции:

  1. Сначала оператор точка ‘.’ возвращает свойство объекта – его метод ( obj.method ).
  2. Затем скобки () вызывают этот метод (исполняется код метода).

Итак, каким же образом информация о this передаётся из первой части во вторую?

Если мы поместим эти операции в отдельные строки, то значение this , естественно, будет потеряно:

let user = < name: "John", hi() < alert(this.name); >>; // разделим получение метода объекта и его вызов в разных строках let hi = user.hi; hi(); // Ошибка, потому что значением this является undefined

Здесь hi = user.hi сохраняет функцию в переменной, и далее в последней строке она вызывается полностью сама по себе, без объекта, так что нет this .

Для работы вызовов типа user.hi() , JavaScript использует трюк – точка ‘.’ возвращает не саму функцию, а специальное значение «ссылочного типа», называемого Reference Type.

Читайте также:  Фонарики для css v34

Этот ссылочный тип (Reference Type) является внутренним типом. Мы не можем явно использовать его, но он используется внутри языка.

Значение ссылочного типа – это «триплет»: комбинация из трёх значений (base, name, strict) , где:

  • base – это объект.
  • name – это имя свойства объекта.
  • strict – это режим исполнения. Является true, если действует строгий режим ( use strict ).

Результатом доступа к свойству user.hi является не функция, а значение ссылочного типа. Для user.hi в строгом режиме оно будет таким:

// значение ссылочного типа (Reference Type) (user, "hi", true)

Когда скобки () применяются к значению ссылочного типа (происходит вызов), то они получают полную информацию об объекте и его методе, и могут поставить правильный this ( user в данном случае, по base ).

Ссылочный тип – исключительно внутренний, промежуточный, используемый, чтобы передать информацию от точки . до вызывающих скобок () .

При любой другой операции, например, присваивании hi = user.hi , ссылочный тип заменяется на собственно значение user.hi (функцию), и дальше работа уже идёт только с ней. Поэтому дальнейший вызов происходит уже без this .

Таким образом, значение this передаётся правильно, только если функция вызывается напрямую с использованием синтаксиса точки obj.method() или квадратных скобок obj[‘method’]() (они делают то же самое). Существуют различные способы решения этой проблемы: одним из таких является func.bind().

Итого

Ссылочный тип – это внутренний тип языка.

Чтение свойства, например, с точкой . в obj.method() возвращает не точное значение свойства, а специальное значение «ссылочного типа», в котором хранится как значение свойства, так и объект, из которого оно было взято.

Это нужно для последующего вызова метода () , чтобы получить объект и установить для него this .

Для всех остальных операций ссылочный тип автоматически становится значением свойства (в нашем случае функцией).

Вся механика скрыта от наших глаз. Это имеет значение только в особых случаях, например, когда метод динамически извлекается из объекта с использованием выражения.

Источник

What are JavaScript Pointers

People often criticize JavaScript for being a basic language; however, a closer examination reveals that it deals with complexity itself. For instance, in other programming languages such as Golang, C, and C#, the “&” operator is utilized to create “pointers,” which refer to a particular memory location. You may think of the absence of pointers functionality in JavaScript, but that’s not the case. JavaScript does have pointers though they are implemented differently.

Читайте также:  Image source code in css

This write-up will discuss JavaScript pointers and how they work for primitive data types and objects. So, let’s start!

What are JavaScript Pointers

In JavaScript, “Object References” are called “Pointers”. Instead of explicitly storing a primitive or object value, these pointers save the memory address where the data is stored. Thus, the stored memory address can be used to refer to the data indirectly.

Working of JavaScript Pointer

When the assignment operator “=” is utilized with objects, this operation creates an alias (references) for the original object rather than creating a new object. So making any changes in the “reference” will also affect the original object. Whereas, in the case of primitive data types such as an array, string, and boolean, a copy of the original variable is created, and altering or reassigning the reference variable will not modify the original variable.

We will now practically implement the functionality of JavaScript pointers for the primitive and non-primitive values.

Example 1: Using JavaScript Pointers

First of all, we will create an “object literal” named “ref” having the following “key-value” pair:

Next, we will create a “pointer()” function that accepts an “object” as an argument that increment its “number” property value:

Then, we will pass the “ref” object” to the “pointer()” function:

Open up your HTML file in the browser and press “CTRL+SHIFT+j” to activate the console mode:

Output

In the above-given program, the reference of the “ref” object is copied over the “object,” and both “object” and “ref” refer to the same “name-value” pair in the memory. This statement also signifies that changing the value of the “number” property un the “pointer()” function will also affect the “number” property of “ref”.

Check out the below-given gif to have a better understanding of the execution process:

Example 2: Using JavaScript Pointers

In this example, we will add a paragraph element

with a “references” id:

After doing so, we will declare a “games” object having two “name-value” pairs. Then, we will assign the “games” object as a reference to the paragraph element as its inner HTML content:

Читайте также:  What is meta title in html

var games = { outdoor : «cricket» , indoor : «ludo» } ;

document. getElementById ( «references» ) . innerHTML = games ;

The given output states that currently, the paragraph element is referring to an “Object”:

To access the value of “games.indoor” property, we will add the following line in our “index.html” file:

As you can see, now the paragraph element has successfully accessed the value of the “games.indoor” property:

Till this point, you may have understood how object references work in JavaScript for objects. In the next example, we will check out the working of JavaScript pointers for the primitive data types.

Example 3: Using JavaScript Pointers

In our program, we have declared an array named “array1” and then created a reference “ref” of the original array:

After that, we will push an element to “array1”. This action will also add the specified element to the “ref” variable because the created reference is the copy of the original array:

console. log ( «array : » , array1 ) ;

console. log ( «reference : » , ref ) ;

Output

However, specifically changing the values of the “ref” variable will not modify the original “array1” values:

console. log ( «Reference» , ref ) ;

console. log ( «Original array» , array1 ) ;

The given output shows that values of the “ref” variable are altered, but it the “array1” comprises the same original values and has not changed:

We have compiled the basic information related to JavaScript pointers. You can further explore this topic according to your preferences.

Conclusion

Object References are also called JavaScript Pointers. Instead of explicitly storing a primitive or object value, the JavaScript pointers save the memory address where the data is stored. Thus, the stored memory address can then indirectly refer to the data. This write-up discussed JavaScript pointers and how they work for primitive data types and objects.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

Источник

Оцените статью