對(duì)象標(biāo)簽,對(duì)象序列化
- [[proto]]
- [[class]]
- [[extensible]]
原型標(biāo)簽 proto 懈贺。
class標(biāo)簽梭灿,表示對(duì)象屬于哪個(gè)類型
var toString = Object.prototype.toString;
function getType(o) {
return toString.call(o).slice(8, -1);
}
toString.call(null); // "[Object Null]"
getType(null); // "Null"
getType(undefined); // "Undefined"
getType(1); // "Number"
getType(new Number(1)); // "Number"
typeof new Number(1); // "Object"
getType(true); // "Boolean"
getType(new Bollean(true)); // "Boolean"
extensible標(biāo)簽
var obj = {x:1, y:2};
Object.isExtensible(obj); // true
Object.preventExtensions(obj);
Object.isExtensible(obj); // flase
obj.z = 1;
obj.z; // undefined, add new property failed
Object.getOwnPropertyDescriptor(obj, 'x');
// Object {value: 1, writable: true, enumerable: true, configurable: true}
Object.seal(obj);
Object.getOwnPropertyDescriptor(obj, 'x');
//Object {value: 1, writable: true, enumerable: true, configurable: false}
Object.isSealed(obj); // true
Object.freeze(obj);
Object.getOwnPropertyDescriptor(obj, 'x');
//Object {value: 1, writable: false, enumerable: true, configurable: false}
Object.isFrozen(obj); // true
// [caution] not affects prototype chain!!!
序列化
var obj = {
x: 1,
y: true,
z: [1, 2, 3],
nullVla: null
};
JSON.stringify(obj); // "{"x":1,"y":true, "z":[1,2,3], "nullVla": null}"
//如果值是 undefined 堡妒,則不會(huì)出現(xiàn)在序列化中
obj = {
val: undefined,
a: NaN,
b: Infinity,
c: new Date()
};
JSON.stringify(obj); // "{"a":null,"b":null, "c":"2015-02-01T18:35:39.434Z"}"
obj = JSON.parse('{"x":1}');
obj.x; //1
序列化-自定義
var obj = {
x:1,
y:2,
o:{
o1:1,
o2:2,
toJSON: function() {
return this.o1 + this.o2;
}
}
};
JSON.stringify(obj); //"{"x":1, "y":2, "o":3}"
其他對(duì)象發(fā)法
var obj = {x:1, y:2};
obj.toString(); // "[object Object]"
obj.toString = function() {
return this.x + this.y
};
"Result " + obj; // "Result 3", by toString
+obj; // 3, from toString
obj.valueOf = function() {
return this.x + this.y + 100;
};
+obj; // 103, from valueOf
//字符串拼接仍然用 toString
"Result " + obj; //still "Result 3"