Skip to content Skip to sidebar Skip to footer

Using A Function In Two Different Ways

I'm creating a function that attaches to other functions. Like: string('Hi').capitilize()//returns hi I want to be able to use $$.string in two different ways. 1 is attaching it t

Solution 1:

The basic problem is that a function can't tell where it's return value is headed. The call your function is over by the time that the . operator is being evaluated, and therefore your code can't make anything happen at that point.

Now, what you can do is return an object that's got a toString() implementation on its prototype, so that when your object is used in a situation where it'll be treated as a string it'll convert appropriately.

var g = function (a) { 
        this._string = typeof a == "string" ? a : a.toString();
        return a;
}
g.prototype.toString = function() {
  returnthis._string;
}
var string = function (a) {
            returnnewg(a);
}
alert( newstring("Hi") );

Post a Comment for "Using A Function In Two Different Ways"