[JavaScript] toString妙用

题目:
函数add可以实现连续的加法运算
函数add语法如下:

add(num1)(num2)(num3)…; 

使用举例如下:

add(10)(10) = 20
add(10)(20)(50) = 80
add(10)(20)(50)(100) = 180

请使用js代码实现函数add

答案:

function add(n){
    var sum=n,
        fn=function(x){
            sum+=x;
            return fn;
        };
        
    fn.toString=function(){
        return sum;
    };
    
    return fn;
}

alert(add(1)(2)+add(1)(2)(3));  //9

解释:
fn是一个function,类型为Object,
+会默认调用fn的toString方法,
这个toString方法不一定返回一个字符串,
本例中返回了一个数字。

规范:
Ecmascript 2015 P36
7.1 Type Conversion
The ECMAScript language implicitly performs automatic type conversion as needed.
To clarify the semantics of certain constructs it is useful to define a set of conversion abstract operations. The conversion abstract operations are polymorphic; they can accept a value of any ECMAScript language type or of a Completion Record value. But no other specification types are used with these operations.

Ecmascript 2015 P42
7.1.12 ToString (argument)
The abstract operation ToString converts argument to a value of type String according to Table 12:

Table 12 — ToString Conversions

Completion Record:
If argument is an abrupt completion, return argument.
Otherwise return ToString(argument.[[value]]).

Undefined:
Return "undefined".

Null :
Return "null".

Boolean :
If argument is true, return "true".
If argument is false, return "false".

Number :
See 7.1.12.1.

String :
Return argument.

Symbol :
Throw a TypeError exception.

Object :
Apply the following steps:

  1. Let primValue be ToPrimitive(argument, hint String).
  2. Return ToString(primValue).

Ecmascript 2015 P36
7.1.1 ToPrimitive (input, [, PreferredType])
The abstract operation ToPrimitive takes an input argument and an optional argument PreferredType. The abstract operation ToPrimitive converts its input argument to a non-Object type. If an object is capable of converting to more than one primitive type, it may use the optional hint PreferredType to favour that type.
Conversion occurs according to Table 9:

Table 9 — ToPrimitive Conversions
Completion Record :
If input is an abrupt completion, return input.
Otherwise return ToPrimitive(input.[[value]]) also passing the optional hint PreferredType.

Undefined :
Return input.

Null :
Return input.

Boolean :
Return input.

Number :
Return input.

String :
Return input.

Symbol :
Return input.

Object :
Perform the steps following this table.

When Type(input) is Object, the following steps are taken:

  1. If PreferredType was not passed, let hint be "default".
  2. Else if PreferredType is hint String, let hint be "string".
  3. Else PreferredType is hint Number, let hint be "number".
  4. Let exoticToPrim be GetMethod(input , @@toPrimitive).
  5. ReturnIfAbrupt(exoticToPrim).
  6. If exoticToPrim is not undefined, then
    a. Let result be Call(exoticToPrim, input , «hint»).
    b. ReturnIfAbrupt(result).
    c. If Type(result) is not Object, return result.
    d. Throw a TypeError exception.
  7. If hint is "default", let hint be "number".
  8. Return OrdinaryToPrimitive(input ,hint ).

When the abstract operation OrdinaryToPrimitive is called with arguments O and hint, the following steps are taken:

  1. Assert: Type(O) is Object
  2. Assert: Type(hint) is String and it s value is either "string" or "number".
  3. If hint is "string", then
    a. Let methodNames be «"toString", "valueOf"».
  4. Else,
    a. Let methodNames be «"valueOf", "toString"».
  5. For each name in methodNames in List order, do
    a. Let method be Get( O, name).
    b. ReturnIfAbrupt(method).
    c. If IsCallable( method) is true, then
    i. Let result be Call(method, O).
    ii. ReturnIfAbrupt(result).
    iii. If Type(result) is not Object, return result.
  6. Throw a TypeError exception.

**NOTE **
When ToPrimitive is called with no hint, then it generally behaves as if the hint were Number. However, objects may over-ride this behaviour by defining a @@toPrimitive method. Of the objects defined in this specification only Date objects (see 20.3.4.45) and Symbol objects (see 19.4.3.4) over-ride the default ToPrimitive behaviour.
Date objects treat no hint as if the hint were String.

Ecmascript 2015 P169
12.7.3 The Addition operator ( + )
NOTE
The addition operator either performs string concatenation or numeric addition.

Runtime Semantics: Evaluation 12.7.3.1
AdditiveExpression : AdditiveExpression + MultiplicativeExpression

  1. Let lref be the result of evaluating AdditiveExpression.
  2. Let lval be GetValue(lref ).
  3. ReturnIfAbrupt(lval ).
  4. Let rref be the result of evaluating MultiplicativeExpression.
  5. Let rval be GetValue(rref).
  6. ReturnIfAbrupt(rval).
  7. Let lprim be ToPrimitive(lval ).
  8. ReturnIfAbrupt(lprim).
  9. Let rprim be ToPrimitive( rval).
  10. ReturnIfAbrupt(rprim).
  11. If Type(lprim) is String or Type(rprim) is String, then
    a. Let lstr be ToString(lprim).
    b. ReturnIfAbrupt(lstr).
    c. Let rstr be ToString(rprim).
    d. ReturnIfAbrupt(rstr).
    e. Return the String that is the result of concatenating lstr and rstr.
  12. Let lnum be ToNumber(lprim).
  13. ReturnIfAbrupt(lnum).
  14. Let rnum be ToNumber(rprim).
  15. ReturnIfAbrupt(rnum).
  16. Return the result of applying the addition operation to lnum and rnum. See the Note below 12.7.5.

NOTE 1
No hint is provided in the calls to ToPrimitive in steps 7 and 9. All standard objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Exotic objects may handle the absence of a hint in some other manner.

NOTE 2
Step 11 differs from step 5 of the Abstract Relational Comparison algorithm (7.2.11), by using the logical-or operation instead of the logical-and operation.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,869评论 0 6
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,747评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,672评论 18 139
  • 七 我一向对生死离别没有特别的感触,但是在小学的最后一次六一儿童节,却让我对这个地方产生了深深的眷恋,因为一个人,...
    春深君阅读 275评论 0 0
  • 这”缘”字,我是浓墨朴拙之笔:完成!有浓墨也有走笔飞白跃初。结构相互亲合呼应,天趣意成。左部”纟”用篆意...
    欣平气和阅读 750评论 0 0