Object.extend()

jQueryとかにあるやつ。出来てない。

by ethertank

JavaScript

Object.prototype.extend || (Object.prototype.extend = function(e) {
    if (!e && (this !== null) && e instanceof Object !== "object") throw new Error("引数はオブジェクトで!一個だけな!(・∀・)");
    for (var p in e) e.hasOwnProperty(p) && (this[p] = e[p]);
    return this;
});







var o = { a: 1, b: 2, c: 3 }; // object


// 元のオブジェクト
for (p in o) if (o.hasOwnProperty(p)) document.write(p + ": " + o[p] + "<br />");
document.write("<hr \/>");


// test
var e = o.extend({ c: 5, d: 4, e: 5 });
for (p in e) if (e.hasOwnProperty(p)) document.write(p + ": " + e[p] + "<br />");
document.write("<hr \/>");


// 元のオブジェクト
for (p in o) if (o.hasOwnProperty(p)) document.write(p + ": " + o[p] + "<br />");
document.write("破壊的にした(・∀・)<hr \/>");


// error test
try { new Date().extend(); }
catch (e) { document.write(e); }