program tip

JavaScript에서 변수 할당은 어떻게 작동합니까?

radiobox 2020. 8. 27. 07:40
반응형

JavaScript에서 변수 할당은 어떻게 작동합니까?


그래서 저는 자바 스크립트에서 대량 할당이 정확히 어떻게 작동하는지 확인하기 위해 며칠 동안 놀았습니다.

먼저 콘솔에서이 예제를 시도했습니다.

a = b = {};
a.foo = 'bar';
console.log(b.foo);

결과는 경고에 "막대"가 표시되었습니다. 즉 공정의 충분하다, a그리고 b정말 같은 객체 단지 별칭이다. 그런 다음 어떻게이 예제를 더 간단하게 만들 수 있을지 생각했습니다.

a = b = 'foo';
a = 'bar';
console.log(b);

그것은 거의 똑같지 않습니까? 이번에 는 첫 번째 예제의 동작에서 예상했던대로 반환 foo되지 않습니다 bar.

왜 이런 일이 발생합니까?

NB 이 예제는 다음 코드를 사용하여 훨씬 더 단순화 할 수 있습니다.

a = {};
b = a;
a.foo = 'bar';
console.log(b.foo);

a = 'foo';
b = a;
a = 'bar';
console.log(b);

(JavaScript는 문자열과 정수와 같은 프리미티브를 해시와 다르게 취급한다고 생각합니다. 해시는 포인터를 반환하고 "코어"프리미티브는 자신의 복사본을 반환합니다)


첫 번째 예에서는 기존 개체의 속성을 설정합니다. 두 번째 예에서는 새로운 개체를 할당합니다.

a = b = {};

ab같은 객체에 대한 포인터는 지금. 그래서 당신이 할 때 :

a.foo = 'bar';

그것은 설정 b.foo이후뿐만 아니라 ab포인트 같은 객체.

하나!

대신 이렇게하는 경우 :

a = 'bar';

a지금은 다른 대상 가리키고 있습니다. 이것은 a이전에 지적한 것에 영향을 미치지 않습니다 .

JavaScript에서 변수 할당과 속성 할당은 두 가지 다른 작업입니다. 변수를 개체에 대한 포인터로 생각하는 것이 가장 좋습니다. 변수에 직접 할당 할 때는 개체를 수정하지 않고 변수를 다른 개체로 다시 지정하는 것입니다.

그러나 같은 속성을 할당하면 가리키는 a.foo객체가 수정 a됩니다. 물론 이것은 모두 동일한 객체를 가리 키기 때문에이 객체를 가리키는 다른 모든 참조도 수정합니다.


귀하의 질문은 이미 Squeegy에 의해 만족스럽게 답변되었습니다. 객체 대 기본 요소와는 아무 관련이 없지만 동일한 참조 객체에서 변수 재 할당 대 속성 설정과 관련이 있습니다.

답변과 주석에서 JavaScript 유형에 대해 많은 혼란이있는 것 같으므로 다음은 JavaScript의 유형 시스템에 대한 간단한 소개입니다.

자바 스크립트에는 근본적으로 다른 두 종류의 값이 있습니다. 프리미티브와 객체입니다 ( '해시'와 같은 것은 없습니다).

문자열, 숫자, 부울뿐만 아니라 null하고 undefined있다 프리미티브 객체는 속성을 가질 수있는 모든 수 있습니다. 배열과 함수조차도 일반 객체이므로 임의의 속성을 보유 할 수 있습니다. 내부 [[Class]] 속성 만 다를뿐입니다 (함수에는 [[Call]] 및 [[Construct]]라는 속성이 추가로 있지만 세부 사항입니다).

프리미티브 값이 객체처럼 작동하는 이유는 오토 박싱 때문이지만 프리미티브 자체는 속성을 보유 할 수 없습니다.

다음은 예입니다.

var a = 'quux';
a.foo = 'bar';
document.writeln(a.foo);

This will output undefined: a holds a primitive value, which gets promoted to an object when assigning the property foo. But this new object is immediately discarded, so the value of foo is lost.

Think of it like this:

var a = 'quux';
new String(a).foo = 'bar'; // we never save this new object anywhere!
document.writeln(new String(a).foo); // a completly new object gets created

You're more or less correct except that what you're referring to as a "hash" is actually just shorthand syntax for an Object.

In the first example, a and b both refer to the same object. In the second example, you change a to refer to something else.


here is my version of the answer:

obj = {a:"hello",b:"goodbye"}
x = obj
x.a = "bonjour"

// now obj.a is equal to "bonjour"
// because x has the same reference in memory as obj
// but if I write:
x = {}
x.a = obj.a
x.b = obj.b
x.a = "bonjour"

// now x = {a:"bonjour", b:"goodbye"} and obj = {a:"hello", b:"goodbye"}
// because x points to another place in the memory

You are setting a to point to a new string object, while b keeps pointing to the old string object.


In the first case you change some property of the object contained in the variable, in the second case you assign a new value to the variable. That are fundamentally different things. The variables a and b are not somehow magically linked by the first assignment, they just contain the same object. That's also the case in the second example, until you assign a new value to the b variable.


The difference is between simple types and objects.

Anything that's an object (like an array or a function) is passed by reference.

Anything that's a simple type (like a string or a number) is copied.

I always have a copyArray function handy so I can be sure I'm not creating a bunch of aliases to the same array.

참고URL : https://stackoverflow.com/questions/509579/how-does-variable-assignment-work-in-javascript

반응형