例とJavaScriptのリファレンスタイプ入門
前の記事では、私たちは原始的なタイプを見ました.
プリミティブ型とリファレンス型の基本的な違いは、プリミティブ型では値が変数に格納されているのに対し、参照型ではその変数への参照/アドレスが変数に格納されます.両方の違いを理解しましょう.
例:
// primitive
let x = "JS";
let y = x;
console.log(y); // "JS"
x = "Java";
console.log(x); // "Java"
console.log(y); // "JS"
// reference
let a = {language:"JavaScript"};
let b = a;
console.log(b); // {language:"JavaScript"}
a.language = "Java";
console.log(a); // {name:"Java"}
console.log(b); // {name:"Java"}
原始
リファレンス
プリミティブ型とリファレンス型の別の違いは、参照型がヒープに格納されている間にプリミティブ型がスタックに格納されていることです.
プリミティブ型では、Typeof演算子を使用して、指定されたデータ型が原始的かどうかを確認しますが、参照型では、指定された型が参照型かどうかを調べるには、InstanceOf演算子を使用します.
JavaScriptは3つの参照データ型を持っています、我々は例で各々を理解します.
1. Arrays
2. Functions
3. Objects
アレイ
In JavaScript, if you assign an array to a variable it is the reference to the array that the variable holds not the value so any changes to the array will reflect on the original array lets us look at an example to understand better
例
let languages = ["c","c++","java"];
let lang = languages;
languages[2] = "javascript";
console.log(lang); // ["c","c++","javascript"]
関数
In functions when you pass primitive type data, any changes only happen to formal arguments but doesn't reflect on actual arguments. Let us look at an example.
function foo(val){
val+="script";
}
let lang = "java";
let result = foo(lang);
console.log(lang); // java
console.log(result); // javascript
In the above example, you can see that changes in the formal arguments are not reflected in actual arguments.
However, in reference types when you can pass an object to a function you can modify its properties but not the object. Look at the example below to understand better
// Example 1
function modifyProperty(obj){
obj.value = 10;
}
let x = {
value : 1;
}
modifyProperty(x);
console.log(x); // { value : 10}
// Example 2
function modifyObject(obj){
obj = {
value = 20;
}
}
ley y = { value: 2 };
modifyObject(y);
console.log(y); // {value:2}
オブジェクト
In JavaScript, a variable that stores an object is accessed by its reference instead of value.
Refer to the first example to get a better understanding.
Thank you for reading the article please give your feedback and suggestions below in the comments.
Reference
この問題について(例とJavaScriptのリファレンスタイプ入門), 我々は、より多くの情報をここで見つけました https://dev.to/vineethsagar/introduction-to-reference-types-in-javascript-33m2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol