DCSIMG
Bending JavaScript - מקודד לשווא

Bending JavaScript

A client of mine faced me with an odd problem , what he wanted is to have an accessor  (proxy method) for a property in an object.


var Person = function(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}

my first response was no problem , just create a function to wrap the property:


Person.prototype.FirstName = function(firstname) {
    if (firstname != null && typeof (firstname) == "string") {
        this.firstname = firstname;
    }
    return this.firstname;
}

maybe you might know this type of get/set style of programming from Jquery,  where a wrapper function is acting both as setter & getter e.g.


var friend = new Person("avvi", "seftel");
// set
friend.FirstName("aviv");
// get
var friendName = friend.FirstName();

that technique worked well except that the client wanted to maintain his current API’s , so after a some poking around i did a few tests and came up with the following ruse:


var StringProxy = function (value){
    this.value  = value;
}
StringProxy.prototype = new String();
StringProxy.prototype.valueOf = function() {
    return this.value
}
StringProxy.prototype.toString = function() {
    return String(this.valueOf());
}
   

var Person = function(firstname, lastname) {
    this.firstname = new StringProxy(firstname);
    this.lastname = new StringProxy(lastname);
}



var friend = new Person("aviv", "seftel");
// get
var name = friend.firstname;

by overloading toString & valueOf methods i was able to create an proxy function (for now it’s read only) and maintain API backward compatibility

Published Sunday, March 08, 2009 7:44 PM על ידי danielisimo
תגים:,

תוכן התגובה

# re: Bending JavaScript

Sunday, March 08, 2009 10:36 PM על ידי Avi Pinto

nice

שלח תגובה

(שדה חובה) 
(שדה חובה) 
(אופציונלי)
(שדה חובה) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems