Posted By

Sephr on 03/05/09


Tagged

accessor js18 getter setter


Versions (?)

Get Accessor (Getter/Setter) [JS 1.8]


 / Published in: JavaScript
 

Requires JavaScript 1.8

$[gs]etter(obj, property) returns function() obj.__lookup[GS]etter__(property).apply(obj, Array.prototype.slice.call(arguments))

object.get[GS]etter(property) returns $[gs]etter(this, property)

Useful for getting the getters and setters of objects like location, so you can do stuff like location.getSetter("hash") to get the native hash-changing function.

Example:

var foo = {a: 5}
foo.__defineSetter__("bar", function(x) x/this.a)
var fooBarSetter = foo.getSetter("bar") // $setter(foo, "bar") also works
fooBarSetter(40) == 8

var changeHash = location.getSetter("hash")
changeHash("test")
var getHash = location.getGetter("hash")
getHash() == location.hash
getHash() == "#test"

function changeInnerHTML(el, html) el.getSetter("innerHTML")(html)
changeInnerHTML(document.body, "test")
document.getSetter("title")("Test")
  1. function $setter(obj, prop) function() obj.__lookupSetter__(prop).apply(obj, Array.prototype.slice.call(arguments));
  2. function $getter(obj, prop) function() obj.__lookupGetter__(prop).apply(obj, Array.prototype.slice.call(arguments));
  3.  
  4. Object.prototype.getSetter = function(prop) $setter(this, prop);
  5. Object.prototype.getGetter = function(prop) $getter(this, prop);

Report this snippet  

You need to login to post a comment.