T
T
t332712018-05-29 09:08:57
JavaScript
t33271, 2018-05-29 09:08:57

Why is the order in which the object key is output in this way?

I'm learning JavaScript and there's an example in the book.

function f(o) {
  o.message = "Изменено в f";
  o = {
    message: "Новый объект!"
  };

console.log (`Внутри f: o.message="${o.message}" (после присваивания)`);
}

let o = {
  message: 'Начальное значение'
};

console.log(`Перед вызовом f: o.message="${o.message}"`);
f(o);
console.log(`После вызова f: o.message="${o.message}"`);

The result of execution is as follows:
Before calling f: o.message="Initial value"
Inside f: o.message="New object!" (after assignment)
After calling f: o.message="Changed in f"
Question
Why is "New object!" instead of "Changed in f" displayed in the string when the first thing in the body of the function is The matter of precedence of operators or there is some another rule? Strongly do not scold if the question is stupid, I'm a beginner, I tried to google, but completely different topics came out.
o.message = "Изменено в f";
spoiler
В самом учебнике этому не уделено внимание.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-05-29
@t33271

Because in the function f you have assigned a new object to the local variable (argument) o :

{
  message: "Новый объект!"
}

Outside the function, the global o refers to the old object in which you changed the key message to "Changed in f" during the call to f . In other words, during the first and third console.log calls, the key of the old object is printed, during the second new one. A good example demonstrating the basic principles of the language. Passing by reference Scope

A
Andrey Panov, 2018-05-29
@PanovAndrey

Read what console.log does. And for one thing, how assignment works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question