javascript TypeError:找不到函数startsWith



我有一个javascript函数:

           string.prototype.startsWith = function(str) {
               return (this.indexOf(str) === 0);
           }

当我在typeof返回object的东西上运行它时,它就工作了。当我在typeof返回string的东西上运行它时,我得到:

javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function startsWith. (<Unknown source>#29) in <Unknown source> at line number 29

有人知道发生了什么事吗?我甚至不明白为什么我使用的第一个东西的实例类型是对象。这是readLine调用的结果,不应该是字符串吗?

<target name="analyze">
    <script language="javascript">
    <![CDATA[
            importClass(java.io.File);
            importClass(java.io.FileReader)
            importClass(java.io.BufferedReader)
            //setup the source directory
            dir = project.getProperty("PROJECT_HOME");
            fs = project.createDataType("fileset");
            fs.setDir(new File(dir));
            //only analyze java files
            fs.setIncludes("**/*.java");
            echo = project.createTask("echo");
            //iterate over files found
            srcFiles = fs.getDirectoryScanner(project).getIncludedFiles();
            for (i = 0; i < srcFiles.length; i++) {
                var filename = srcFiles[i];
                inFile  = new BufferedReader(new FileReader(new File(dir + "/" + filename)));
                while ((line = inFile.readLine()) != null) {
                   if(line.startsWith("package")) {
                       packageStr = line.substr(8);
                       while((line = inFile.readLine()) != null) {
                           if(line.startsWith("import") && line.endsWith("Foo;")) {
                               //strip out the leading import in 'import x.y.z'
                               var importStr = line.substr(7);
                               importStr = importStr.substr(0, importStr.lastIndexOf('.'));
                               if(!importStr.startsWith(packageStr)) { <---- FAILS!
                               }
                           }
                       }
                   }
                }
                inFile.close();
           }
           String.prototype.startsWith = function(str) {
               return (this.indexOf(str) === 0);
           }
           String.prototype.endsWith = function(str) {
               var lastIndex = this.lastIndexOf(str);
               return (lastIndex != -1) && (lastIndex + str.length == this.length);
           }
    ]]>
    </script>
</target>

我认为问题是在定义starstWith函数之前先调用它。也许应该在for块之前放置两个函数定义。通过这种方式,在调用它们之前对它们进行评估。

尝试大写S:

String.prototype.startsWith = function(str) {
               return (this.indexOf(str) === 0);
           }

相关内容

  • 没有找到相关文章

最新更新