Javascript 参照

参照、コピーとかです

プリミティブ型とオブジェクト型

・データ型ではプリミティブ型とオブジェクトが存在する。

・オブジェクトは参照を名前付きで管理している入れ物である。
プロパティが値を管理している。そのプロパティを管理している。

プリミティブ値のコピー 
・参照先の値がコピーされる

オブジェクトのコピー
・オブジェクトへの参照がコピーされる( {}がコピーされる)

参照

let a = ‘hello’
このときaはhelloへの参照を保持していると言える。
constの際は固定化される
参照先のみロックするため、オブジェクト内の値を変更することは可能

const c = {
   prop:'hello'
}
c.prop = 'aaaa';
console.log(c); //aaaa

参照と引数

プリミティブ型の値を関数の引数にする場合、
引数の値と、関数内の値は
お互いに影響は受けない

プリミティブ型の参照

let a = 0;
function fn1(arg1){
arg1 = 1;
console.log(a,arg1); // 0,1
}
fn1(a);

オブジェクト型の参照1 プロパティ内の値

let b = { prop:0 }
function fn2(arg2){
arg2.prop = 1;
console.log(b,arg2); //prop:1 prop:1 {}を参照するため、中の値を変更するとその値も変わる
}
fn2(b);

オブジェクト型の参照2 {}

function fn3(arg2){
arg2 = {};
console.log(b,arg2); //{prop:1} , {}
}
fn3(b);

分割代入

let (a) = object;
オブジェクトから特定のプロパティを抽出して宣言を行う

const a = {
prop:0
}
let {prop} = a; // prop が保存される 分割代入
prop = 1;
console.log(prop); // 1

関数内

function fn(obj){
let { prop } = obj;
prop= 1;
console.log(a,prop); // prop:0 1
}
/*-- この書き方でもできるよ
function fn({prop}){
prop= 1;
console.log(obj,prop);
}
--*/
fn(a);
オブジェクト内のオブジェクト
const c = {
prop1:{
prop2:0
}
}
let {prop1} = c;
console.log(prop1); //prop1 0
prop1.prop2 = 1;
console.log(c,prop1); //prop1:prop2:1,prop2:1

参照の比較と値の比較

・プリミティブ型では値の比較

・オブジェクトは参照の比較

const a = {
prop:0
}
const b = {
prop:0
}
console.log(a === b); //false
console.log(a.prop === b.prop); //true
const c = a;
console.log(a === c); //true

投稿者 @rongai