Skip to content

Instantly share code, notes, and snippets.

@creationix
Created August 12, 2010 00:15
Show Gist options
  • Save creationix/520067 to your computer and use it in GitHub Desktop.
Save creationix/520067 to your computer and use it in GitHub Desktop.
An experience in making an object library.
Object.defineProperty(Object.prototype, "extend", {value: function (obj) {
obj.__proto__ = this;
return obj;
}});
Object.defineProperty(Object.prototype, "new", {value: function () {
var obj = Object.create(this);
if (obj.initialize) obj.initialize.apply(obj, arguments);
return obj;
}});
var Rectangle = {
initialize: function initialize(width, height) {
this.width = width;
this.height = height;
},
get area() {
return this.width * this.height;
}
};
var Square = Rectangle.extend({
initialize: function initialize(side) {
this.width = side;
this.height = side;
}
});
var rect = Rectangle.new(10, 20);
console.log(rect.area);
var square = Square.new(15);
console.log(square.area);
@akidee
Copy link

akidee commented Aug 12, 2010

1) Is "Rectangle['new'](10, 20);" nice? (Is "new" reserved keyword in ES5? I think so.)
2) __proto__ slowness ;)
3) Polluting Object.prototype ... but this should by allowed in the context of experimenting ;)

@creationix
Copy link
Author

  1. I know new is reserved, but I think it should be removed from the language. And my code works today in ES5 capable engines
  2. __proto__ isn't slower than Object.create and then manually copying stuff on top. Plus it's hard to copy special properties.
  3. I'm almost proposing a language change here, so anything is valid in the name of experimenting. Besides, Object.defineProperty "pollutes" it properly.

@shimondoodkin
Copy link

do i copy it correctly?

function copy(target,newobject) // replace and delete
{
 if(newobject.constructor) target.constructor=newobject.constructor; // is this works?
 if(newobject.__proto__) target.__proto__=newobject.__proto__; // is this works?
 if(newobject.prototype) target.prototype=newobject.prototype; // is this works?

 //replace
 for(var i in newobject)
 {
  if(newobject.hasOwnProperty(i))
   target[i]=newobject[i];
 }
 //delete
 for(var i in target)
 {
  if(target.hasOwnProperty(i) && (!(i in newobject)) )  delete target[i];
 }
};exports.copy=copy;

@akidee
Copy link

akidee commented Aug 12, 2010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment