数字直接调用函数:(5).fn1(2).fn2(3)实现5-2+3

栏目: JavaScript · 发布时间: 7年前

内容简介:在网上无意间看到这么一道题,第一次实践,直接报错,所以记录下来加深记忆一看到数字可以调用函数,最先想到的类似的场景就是1、重写Number原型对象中的方法

起因

在网上无意间看到这么一道题,第一次实践,直接报错,所以记录下来加深记忆

过程

一看到数字可以调用函数,最先想到的类似的场景就是 (5).toFixed(2) ,那么接下来,有两个思路了

1、重写Number原型对象中的方法

2、在Number的原型对象中添加方法

思路一在实践过程中,终于在 bind 方法中迷失了自我,最后放弃治疗,先记下来以后再战。

思路二,本人没有仔细考虑,直接写了下面一段代码

Number.prototype.fn1 = function (item){
    const value = this.valueOf(); // value

    const result = value - item;

    return result;
};
        
Number.prototype.fn2 = function (item){
    const value = this.valueOf(); // value

    const result = value + item;

    return result;
}
        
console.log((5).fn1(2).fn2(3));

结果就是报错: fn1 未定义

打断点,发现没有调用 fn1 ,而是在 fn2 定义的时候直接报错,在控制台打印 Number.prototype ,发现 fn1 在打印出的对象中, fn2 却没有出现。

一番死脑筋的查询资料,最终在mdn上,发现 Number.prototypeconfigurable 属性为 false

解决

那么问题好办了, Number.prototype 继承于 Object.prototypeObject.prototypeconfigurable 属性值是 true 。更改代码如下

Object.prototype.fn1 = function (item){
    const value = this.valueOf(); // value

    const result = value - item;

    return (result);
    // return result; 不加()的话,后面的.会被识别为小数点哦
};
        
Object.prototype.fn2 = function (item){
    const value = this.valueOf(); // value

    const result = value + item;

    return result;
}
        
console.log((5).fn1(2).fn2(3));

ok,问题到这里结束,另外,随手查了 String.prototypeBoolean.prototype ,它们的 configurable 属性值也是 false

遗留问题

其实,删除掉上述 Number.prototype.fn2 ,只执行 (5).fn1(2) 是可以的,为什么加一个属性可以,加两个却不行,正在研究,也希望有高人解答。

Number.prototype.fn1 = function (item){
    const value = this.valueOf(); // value

    const result = value - item;

    return (result);
};
        
console.log((5).fn1(2));

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms on Strings, Trees and Sequences

Algorithms on Strings, Trees and Sequences

Dan Gusfield / Cambridge University Press / 1997-5-28 / USD 99.99

String algorithms are a traditional area of study in computer science. In recent years their importance has grown dramatically with the huge increase of electronically stored text and of molecular seq......一起来看看 《Algorithms on Strings, Trees and Sequences》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具