Skip to content

Instantly share code, notes, and snippets.

@autre
Created May 29, 2011 16:22
Show Gist options
  • Save autre/997910 to your computer and use it in GitHub Desktop.
Save autre/997910 to your computer and use it in GitHub Desktop.
// Clone this object and (optionally) append
// own properties of `other_object` to the newly cloned one.
// This is a convenience method over the Object#create
// Initial code from here: http://howtonode.org/prototypical-inheritance
// Amended with: http://msdn.microsoft.com/en-us/library/ff877835(VS.94).aspx,
// the part about the clone function.
Object.defineProperty(Object.prototype, 'clone', {
get: function() {
var self = this;
return function(other) {
var cloned = Object.create(self);
if (!Object.isExtensible(self))
return Object.preventExtensions(cloned);
if (!other || typeof other != 'object')
return cloned;
Object
.getOwnPropertyNames(other)
.forEach(function(property) {
Object.defineProperty(cloned, property, Object.getOwnPropertyDescriptor(other, property));
});
return cloned;
};
}
});
var puts;
if (typeof require == 'undefined') // rhino before modules
puts = print;
else // node
puts = require('sys').puts;
function uber(obj) { return Object.getPrototypeOf(obj); }
var p1 = Object.prototype.clone({
x: 0,
y: 1,
add: function(other) {
return this.clone({ x: this.x + other.x, y: this.y + other.y });
},
toString: function() {
return this.x + '@' + this.y;
},
});
puts(p1); // 0@1
var p2 = p1.clone({
color: '#green',
toString: function() {
return this.color + ': ' + uber(this).toString();
},
});
puts(p2); // #green: 0@1
var traits_point = Object.prototype.clone({
toString: function() {
return this.x + '@' + this.y;
},
add: function(other) {
return this.clone({ x: this.x + other.x, y: this.y + other.y });
},
});
var p0 = traits_point.clone({ x: 0, y: 0 });
var p1 = traits_point.clone({ x: -1, y: 2 });
puts(p0); // 0@0
puts(p0.add(p1)); // -1@2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment