JS - 对象(5)

对象标签,对象序列化

  • [[proto]]
  • [[class]]
  • [[extensible]]

原型标签 proto

class标签,表示对象属于哪个类型

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标签

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 ,则不会出现在序列化中
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}"

其他对象发法

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"

你可能感兴趣的:(JS - 对象(5))