Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Number.method('integer', function ( ) {
return Math[this < 0 ? 'ceil' : 'floor'](this);
});
document.writeln((-10 / 3).integer( )); // -3
String.method('trim', function ( ) {
return this.replace(/^\s+|\s+$/g, '');
});
document.writeln('"' + " neat ".trim( ) + '"');
上述3段代码 展现了 函数式编程的魅力之一
函数1在初始函数处定义了一个函数 函数赋值给函数本体的 参数函数
函数2在定义的函数 因为在初始函数定义了method 所以 可以直接调用 并传递 函数到 prototype 中
函数3同理
本文介绍了三种函数式编程技巧,包括自定义Function.prototype方法,为Number和String类型添加自定义函数,如整数化和字符串修剪。这些技巧展示了如何扩展JavaScript内置类型的功能。
4672

被折叠的 条评论
为什么被折叠?



