我正在创建一个附加到其他功能的功能.
I'm creating a function that attaches to other functions.
赞:
string("Hi").capitilize()//returns hi我希望能够以两种不同的方式使用$$.string.1正在将其附加到功能上.第二个是单独的功能:
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")那应该只是返回Hi.但是我得到的只是: [object Object]
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.
如果我只有string("Hi"),是否可以使它仅返回字符串,而如果添加它们,仍然允许函数正常工作?
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.
现在,您可以做的是返回一个在其原型上具有 toString()实现的对象,以便在将对象视为字符串的情况下使用该对象时它将进行适当的转换.
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") );更多推荐
以两种不同方式使用函数
发布评论