Return to Snippet

Revision: 12204
at March 5, 2009 16:42 by Sephr


Updated Code
function $setter(obj, prop) {
  return function() {
    return obj.__lookupSetter__(prop).apply(obj, Array.prototype.slice.call(arguments))
  }
}

function $getter(obj, prop) {
  return function() {
    return obj.__lookupGetter__(prop).apply(obj, Array.prototype.slice.call(arguments))
  }
}

Object.prototype.getSetter = function(prop) { return $setter(this, prop) }
Object.prototype.getGetter = function(prop) { return $getter(this, prop) }

Revision: 12203
at March 5, 2009 16:30 by Sephr


Initial Code
function $setter(obj, prop) {
  return function() {
    obj.__lookupSetter__(prop).apply(obj, Array.prototype.slice.call(arguments))
  }
}

function $getter(obj, prop) {
  return function() {
    obj.__lookupGetter__(prop).apply(obj, Array.prototype.slice.call(arguments))
  }
}

Object.prototype.getSetter = function(prop) { return $setter(this, prop) }
Object.prototype.getGetter = function(prop) { return $getter(this, prop) }

Initial URL

                                

Initial Description
`$[gs]etter(obj, property)` returns `function() { return 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) { return 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) { return el.getSetter("innerHTML")(html) }
    changeInnerHTML(document.body, "test")
    document.getSetter("title")("Test")

Initial Title
Get Accessor (Getter/Setter)

Initial Tags

                                

Initial Language
JavaScript