Created
December 29, 2012 04:37
-
-
Save mattjmorrison/4404587 to your computer and use it in GitHub Desktop.
Getter / Setter style properties for javascript... sorta
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var console = { | |
log: function(message){ | |
$('body').append(message + "<br />"); | |
} | |
}; | |
var __bind_prop = function(fn, me, name){ | |
return function(){ | |
var args = [name]; | |
for (var x=0;x<arguments.length;x++){ | |
args.push(arguments[x]); | |
} | |
return fn.apply(me, args); | |
}; | |
}; | |
function Model(){ | |
for (var p in this){ | |
if (this.hasOwnProperty(p)){ | |
this['_' + p] = this[p]; | |
this[p] = __bind_prop(this.__property, this, p); | |
} | |
} | |
} | |
Model.prototype.__property = function(field, value){ | |
if (value !== undefined){ | |
this['_' + field] = value; | |
} | |
return this['_' + field]; | |
}; | |
function Something(firstName, lastName){ | |
this.firstName = firstName; | |
this.lastName = lastName; | |
Model.call(this); | |
} | |
Something.prototype = new Model(); | |
Something.prototype.fullName = function(){ | |
return this.firstName() + " " + this.lastName(); | |
}; | |
var something = new Something('Matthew', 'Morrison'); | |
console.log("Original"); | |
console.log(something.fullName()); | |
something.firstName('Kyle'); | |
something.lastName("Carlton"); | |
console.log("Updated"); | |
console.log(something.fullName()); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsfiddle.net/c83L3/8/