(JavaScript)
JavaScript Object
宿主物件
Host Object
原生物件
Native Object
原生物件
Native Object
JavaScript本身提供的物件、使用者定義的物件
{Array、Date、Math、RegExp、Number、String、Boolean、Object、JSON、Console、Attribute}
宿主物件
Host Object
在執行環境中所額外提供的物件
{window、global...}
root node
object node
//所有物件都是由根物件開始連結
window
document
frames
history
location
screen
navigator
link
images
forms
0x001
0x002
0x003
0x004
其實物件就像是隻寶可夢。
var 皮卡丘 = {
Type : "Electric",
Weight : 10.69,
Height : 0.52,
thunderbolt :
function(){
return 55;
}
};
key
Value
Property
var 皮卡丘 = {
Type : "Electric",
Weight : 10.69,
Height : 0.52,
thunderbolt :
function(){
return 55;
}
};
var 皮卡丘 = {};
//var 皮卡丘 = new Object();
//var 皮卡丘 = Object.create(null);
皮卡丘.Type = "Electric";
皮卡丘.Weight = 10.69;
皮卡丘.Height = 0.52;
皮卡丘.thunderbolt = function(){
return 55;
};
物件的建立
物件的傳遞
var a = 1;
var b;
b = a;
a = "寶可夢";
console.log(a);
//寶可夢
console.log(b);
//1
var a = {name:"皮卡丘"};
var b;
b = a;
a.name = "寶可夢";
console.log(a);
//{name: "寶可夢"}
console.log(b);
//{name: "寶可夢"}
By Reference
By Value
vs
a => 0x001 b => 0x002
a => 0x001 b => 0x001
var aaa = {name:”john”};
function run(xyz) {
xyz.name=“mark”;
}
run(aaa);
console.log(aaa);
物件的記憶體存放(1)
var a = 1, b = 2;
var obj = {
a: 1,
b: 2
};
obj
b
a
0xd4
2
1
1
2
a
b
0xd4
stack
heap
(不是堆積)
物件的記憶體存放(2)
var a = 1, b = 2;
var obj = {
a: 1,
b: 2
};
function swap(p){
p.a = obj.a;
p.b = obj.b;
}
obj
b
a
0xd4
2
1
1
2
a
b
0xd4
stack
heap
0xd4
p
Name space
在javascript中物件也是個容器(container),
因此便可透過物件去達成類似name space的效果。
var 皮卡丘 = {};
var 雷丘 = {};
皮卡丘.thunderbolt = function(){
return 55;
};
雷丘.thunderbolt = function(){
return 85;
};
JSON
(Java Script Object Notation)
{
"name" : "皮卡丘",
"Type" : "Electric",
"Weight" : 10.69,
"Height" : 0.52,
}
Object to JSON
JSON.stringify(皮卡丘);
/*
"{
"name" : "皮卡丘",
"Type" : "Electric",
"Weight" : 10.69,
"Height" : 0.52,
}"
*/
var 皮卡丘 = {
name : "皮卡丘",
Type : "Electric",
Weight : 10.69,
Height : 0.52,
};
JSON to Object
var 皮卡丘 = JSON.parse('{
"name" : "皮卡丘",
"Type" : "Electric",
"Weight" : 10.69,
"Height" : 0.52,
}');
皮卡丘;
/*
Object {
name : "皮卡丘",
Type : "Electric",
Weight : 10.69,
Height : 0.52,
}
*/
Reference-counting garbage collection algorithm
function f(){
var o = {};
var o2 = {};
o.a = o2; // o references o2
o2.a = o; // o2 references o
return "azerty";
}
f();
Problem: cycles
Mark-and-sweep algorithm
(solve the circle problem)