Skip to content

Instantly share code, notes, and snippets.

@vzarytovskii
Created November 21, 2011 08:51
Show Gist options
  • Save vzarytovskii/1382070 to your computer and use it in GitHub Desktop.
Save vzarytovskii/1382070 to your computer and use it in GitHub Desktop.
(function (window,undefined) {
var Interface = function(interface) { return interface };
Object.prototype.clone = function () {
var o = this;
if(!o || "object" !== typeof o)
return o;
var c = "function" === typeof o.pop ? [] : {};
var p, v;
for(p in o) {
if(o.hasOwnProperty(p)) {
v = o[p];
if(v && "object" === typeof v)
c[p] = v.clone();
else
c[p] = v;
}
}
return c;
};
Object.prototype.can = function (methodName) {
return typeof this[methodName] === "function";
};
Object.prototype.exists = function (property) {
return !!this[property];
};
Object.prototype._implements = function (Interface) {
var object = this.prototype;
for (var member in Interface)
if(!object.exists(member))
throw new Error('Object' + object +' failed to implement interface member "' + member + '"');
return true;
};
Object.mixin = function(dst, src) {
for(var prop in src) {
if(!src.hasOwnProperty(prop))
continue;
dst[prop] = src[prop];
}
return dst;
};
Object.prototype.inherit = function(proto) {
var that = this;
proto = proto || {};
var constructor = proto.hasOwnProperty('constructor') ? proto.constructor : function() { that.apply(this, arguments); };
var F = function() {};
F.prototype = this.prototype;
constructor.prototype = Object.mixin(new F(), proto);
constructor.superclass = this.prototype;
constructor.prototype.constructor = constructor;
if(!!proto.__implements__)
constructor._implements(proto.__implements__);
return constructor;
};
})(window);
//////////// Examples:
/*
var IPoint = new Interface({
constructor: function(x,y) {},
isa: function() {},
draw: function() {},
move: function(x,y){},
trash: false
});
var ICircle = new Interface({
setRadius: function(r) {}
});
var Point = Object.inherit({
__implements__: IPoint,
constructor: function (x, y) {
this.x = x;
this.y = y;
},
isa: function () {
return 'point';
},
draw: function() {
alert(this.isa());
alert('[x,y]=' + [this.x, this.y]);
},
move: function(x,y) {
this.x = x;
this.y = y;
alert(this.isa() + ' is moved to [x,y]=' + [this.x, this.y]);
}
});
var Circle = Point.inherit({
__implements__: ICircle,
constructor: function (x, y, r) {
Circle.superclass.constructor.call(this, [x,y]); // Вызываем конструктор родителя
this.x = x;
this.y = y;
this.r = r;
},
isa: function () {
return 'circle';
},
draw: function() {
alert(this.isa());
alert('[x,y,r]=' + [this.x, this.y, this.r]);
},
move: function(x,y) {
this.x = x;
this.y = y;
alert(this.isa() + ' is moved to [x,y]=' + [this.x, this.y]);
},
setRadius: function(r) {
this.r = r;
alert(this.isa() + '\'s radius is set to ' + this.r);
}
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment