Ooo err... :-\
A Pen by Keili Olsen on CodePen.
!(function($, window) { | |
window.__ = { | |
}; | |
__.extend = function extend() { | |
if (!arguments.length) return false; | |
var obj = arguments[0]; | |
for (var i = 1, max = arguments.length; i < max; i++) { | |
var arg = arguments[i]; | |
for (var key in arg) { | |
if (arg.hasOwnProperty(key)) { | |
obj[key] = arg[key]; | |
} | |
} | |
} | |
return obj; | |
}; | |
__.define = function define(obj) { | |
var cons = function constructor(data) { | |
var _this = this; | |
data = __.extend({}, obj, data); | |
var methods = {}; | |
function getterSetter(attrName, value) { | |
if (arguments.length === 1) { | |
return data[attrName]; | |
} | |
return data['__' + attrName] = value; | |
} | |
for (var key in data) { | |
var val = data[key]; | |
if (val instanceof Function) { | |
methods[key] = [data[key]]; | |
_this[key] = function() { | |
var args = arguments; | |
methods[key].forEach(function(method, idx) { | |
console.log(args); | |
var result = method.apply(_this, args); | |
if (result === false) { | |
return false; | |
} | |
}); | |
} | |
} else { | |
_this[key] = getterSetter.bind(_this, key); | |
} | |
} | |
_this.toJson = function(propNames) { | |
if (!propNames) { | |
return JSON.stringify(data); | |
} | |
var result = {}; | |
for (var key in propNames) { | |
var propName = propNames[key]; | |
result[propName] = data[propName]; | |
} | |
return JSON.stringify(result); | |
}; | |
}; | |
return cons; | |
}; | |
})(jQuery, this); | |
$(function() { | |
var Claz = __.define({ | |
x: 23, | |
y: 42, | |
message: 'howdy', | |
func: function() { | |
console.log('func ', arguments); | |
} | |
}); | |
var claz = window.claz = new Claz(); | |
// test getter | |
console.log('using getter'); | |
console.log(claz.x()); | |
// test setter | |
console.log('using setter'); | |
claz.x(55); | |
console.log(claz.x()); | |
// test json | |
console.log('full json data'); | |
console.log(claz.toJson()); | |
// test selective json | |
console.log('partial json data'); | |
console.log(claz.toJson(['message', 'x'])); | |
// test wrapped function | |
claz.func(1, 2, 3); | |
}); |
Ooo err... :-\
A Pen by Keili Olsen on CodePen.