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"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,869评论 18 139
  • 序 从最近的js入门系列的阅读量逐步递减,观众老爷的兴趣也不再能够接受一些细节性的地方深度挖掘,让我有了一些思考。...
    zhaolion阅读 1,632评论 5 19
  • 由于工程项目中拟采用一种简便高效的数据交换格式,百度了一下发现除了采用 xml、JSON 还有 ProtoBuf(...
    黄海佳阅读 48,821评论 1 23
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,123评论 6 13
  • 演讲者Tim Urban,读政府专业,拥有写不完的论文,别人都是刚开始就把第一时间写完,而他总在最后一刻惊慌怪兽出...
    karmen123阅读 321评论 0 0