无法从HTML调用Javascript类

时间:2015-01-20 08:16:48

标签: javascript html function web

请查看以下代码

TTSScript.js

   function TTS()
{
    var msg = new SpeechSynthesisUtterance("yohan");
    var voices = window.speechSynthesis.getVoices();

    this.speakText = function()
        {
             window.speechSynthesis.speak(msg);
        }
    }

的index.html

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <script src="/scripts/TTSScript.js"></script>
        <script>
           function speak()
           {
               var msg = new SpeechSynthesisUtterance('Hello World');
               window.speechSynthesis.speak(msg);
           }

           function speak2()
           {
               var TTS = new TTS();
               TTS.speakText();
           }


        </script>
    </head>
    <body>
        <div><button onclick="speak2()">Click me</button></div>
    </body>
</html>

不幸的是,当我点击html页面中的按钮时,我得到的是一个错误。它在下面。

Uncaught TypeError: undefined is not a function (13:42:13:817 | error, javascript)
    at speak2 (public_html/index.html:23:26)
    at onclick (public_html/index.html:31:126)

我对JavaScript不是很熟悉,能不能让我知道为什么我会收到此错误以及如何修复它?

2 个答案:

答案 0 :(得分:2)

声明函数后,其名称将成为(本地)保留的单词。这意味着创建具有相同名称的变量可能会导致一些问题。

我拿了你的代码并改了

var TTS = new TTS();
TTS.speakText();

var tts = new TTS();
tts.speakText();

错误消失了。

答案 1 :(得分:1)

我解决了你的问题......:

  1. 不要将所有资本名称用作变量

    var tts = new TTS(); tts.speakText();

  2. 正确的说话电话是小提琴

    http://jsfiddle.net/bpprwfxa/4/

  3. &#13;
    &#13;
    var msg = new SpeechSynthesisUtterance('Yohan');
    window.speechSynthesis.speak(msg);
    &#13;
    &#13;
    &#13;