本文介绍Javascript的Object对象类型的重点内容。

对象创建

利用原型继承,可以从现有对象继承来创建新的对象,并且保证新对象的继承属性与原型属性隔离,对属性覆盖不会对原型产生影响。

function inherit(p) {
    if(p == null) throw TypeError();
    var t = typeof(p);
    if( t !== "object" && t !== "function" ) {
        throw TypeError();
    }
    
    function f() {};
    f.prototype = p;
    return new f();
}

var o = { x : 'do not change' };
var p = inherit(o); // p: {x:'do not change'}
p.x = 3; // p: {x:3}
o // o: {x:'do not change'}

访问属性

var o = { x : 1 };
'x' in o; // true
'toString' in o; // true

o.hasOwnProperty('x'); //true
o.hasOwnProperty('toString'); //false: toString是继承属性
o.propertyIsEnumerable('x'); //true

注:propertyIsEnumerable()是hasOwnProperty()的增强版本,只有检测到自有属性,并且属性可枚举时才返回true。

原型属性

对象的原型属性prototype是用来继承属性的,原型属性是在实例对象创建之初就设置好的:

  1. 通过直接量创建的对象,原型是Object.prototype 2.使用new创建的对象,使用构造函数的prototype属性作为对象的原型。

功能函数:

对象序列化

对象序列化(serialization)是指将对象的状态转换为字符串,也可将字符串还原为对象。