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 to functions. The 2nd one is the function alone:
string("Hi")
That is suppose to just return Hi. But all i'm getting is: [object Object]
The main code that allows me to do the first one, to attach to functions is:
var g = function (a) {
this._string = typeof a == "string" ? a : a.toString();
return a;
}
var string = function (a) {
return new g(a);
}
Then I have another variable with all of the functions in it and then bind it with prototype.
Is it possible to make this just return the string if I just have string("Hi") and still allow the functions to work if you add them?
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() {
return this._string;
}
var string = function (a) {
return new g(a);
}
alert( new string("Hi") );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.