JavaScript Tutorial 02 #Object#

var o3 = Object.create(Object.prototype); //equals new Object()
//
function inherit(p) {
    if(p==null) throw TypeError();
    if(Object.create) {
        return Object.create(p);
    }

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

var o = {x:1}
o.hasOwnProperty("x"); //true
o.hasOwnProperty("y");
o.hasOwnProperty("toString"); //false

var o = {
    x: 1.0,
    y: 1.0,
    get r() {
        return Math.sqrt(this.x*this.x + this.y*this.y);
    },    
}

var serialnum = {
    $n : 0,
    get next() {
        return this.$n++;
    },
}

/* 给Object.prototype添加一个不可枚举的extend()方法 */
Object.defineProperty(Object.prototype,
    "extend",
    {
        writable: true,
        enumerable: false,
        configurable: true,
        value: function(o) {
            var names = Object.getOwnPropertyNames(o);
            for(var i=0; i<names.length; i++) {
                if(names[i] in this) continue;
                var desc = Object.getOwnPropertyDescriptor(o,names[i]);
                Object.defineProperty(this,names[i],desc);
            }
        }
    });

/* prototype, class, extensible attribute */
/* o.constructor.prototype */

/* json */
o = {x:1, y:{z:[false,null,""]}};
s = JSON.stringify(o);
p = JSON.parse(s);

posted @ 2013-10-18 19:43  LambdaTea  阅读(200)  评论(0编辑  收藏  举报