以两种不同方式使用函数 [英] Using a function in two different ways

查看:50
本文介绍了以两种不同方式使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个附加到其他功能的功能.

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") );

这篇关于以两种不同方式使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆