简体   繁体   English

向String.Prototype添加函数

[英]Adding Function to String.Prototype

While reading Secrets of the JavaScript Ninja , I encountered this code on partial function application: 在阅读《 JavaScript Ninja的秘密》时 ,我在部分函数应用程序中遇到了以下代码:

String.prototype.csv = String.prototype.split.partial(/,\s*/);

var results = ("Mugan, Jin, Fuu").csv();

console.log("results:", results);

But, when I tried to run it in jsfiddle( http://jsfiddle.net/Y2Tv4/ ), I got this error: 但是,当我尝试在jsfiddle( http://jsfiddle.net/Y2Tv4/ )中运行它时,出现此错误:

Uncaught TypeError: Object function split() { [native code] } has no method 'partial' 未捕获的TypeError:对象函数split(){[native code]}没有方法'partial'

How can I add the csv function to the String.Prototype ? 如何将csv函数添加到String.Prototype

below is the code to execute this method and referece taken from @elclanrs given url good one bro. 以下是执行此方法和引用的代码,它们取自@ elclanrs,URL给了一个好兄弟。 Check out this FIDDLE http://jsfiddle.net/Y2Tv4/1/ 看看这个FIDDLE http://jsfiddle.net/Y2Tv4/1/

    Function.prototype.partial = function(){
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function(){
      var arg = 0;
      for ( var i = 0; i < args.length && arg < arguments.length; i++ )
        if ( args[i] === undefined )
          args[i] = arguments[arg++];
      return fn.apply(this, args);
    };
  };

String.prototype.csv = String.prototype.split.partial(/,\s*/);

     var results = ("Mugan, Jin, Fuu").csv();
 console.log(results);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM