以两种不同方式使用函数

编程入门 行业动态 更新时间:2024-10-26 04:20:54
本文介绍了以两种不同方式使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

以两种不同方式使用函数

本文发布于:2023-10-26 21:50:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531447.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两种   函数   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!