2016-06-15 68 views
0

我希望能夠在創建新的SpeechRecognition對象後在SpeechRecognition中設置函數onbroadcast,以便在滿足特定條件時可以在內部調用此函數。設置可在內部調用的外部對象函數

我希望能夠以與您在webkitSpeechRecognition中設置類似onerror之類的方式進行設置。當我在開發人員工具中查看onerror時,看起來它可能通過某種類型的getter/setter完成,如here所述,但我無法確定。

這可能嗎?

recognition.js:

var SpeechRecognition = function() { 
    var recognitionObject = new webkitSpeechRecognition(); 
    recognitionObject.onresult = function (event) { 
     if(event.results.length > 0) { 
      if (onbroadcast !== null && onbroadcast === 'function') { 
       onbroadcast('there are results'); 
      } 
     } 
    } 
    recognitionObject.onerror = function (event) { 
     console.log(event); 
    } 
    recognitionObject.onend = function (event) { 
     console.log(event); 
    } 
    recognitionObject.start(); 
} 

SpeechRecognition.prototype.onbroadcast = null; 

main.js:

var sr = new SpeechRecognition(); 
sr.onbroadcast = function(msg) { 
    document.getElementById('id') = msg; 
} 
+0

'onupdateraw'和'onbroadcast'是未聲明的變量,你是什麼意思?我想你想引用你的'SpeechRecognition'實例的'.onbroadcast' **屬性** - 通常用'this' [但不是在回調中](http://stackoverflow.com/q/20279484/1048572 ) 像這兒。 – Bergi

+0

對不起 - 'onupdateraw'是一個錯字。 – millarnui

+0

我想以某種方式從對象外部設置'onbroadcast',但是從內部調用它(如果它被設置) – millarnui

回答

0

您需要參考onbroadcast爲您的實例(this.onbroadcast)的property。它不會在構造函數的作用域內變成可用的變量。

function SpeechRecognition() { 
    var self = this; // a reference to the instance 
    var recognitionObject = new webkitSpeechRecognition(); 
    recognitionObject.onresult = function (event) { 
     if (event.results.length > 0 && typeof self.onbroadcast === 'function') { 
      self.onbroadcast('there are results'); 
//   ^a property access 
     } 
    }; 
    recognitionObject.onerror = recognitionObject.onend = function (event) { 
     console.log(event); 
    }; 
    recognitionObject.start(); 
} 
+0

「self」是一個保留字@Bergi –

+0

在main.js中設置sr.broadcast後,我可以看到屬性已經設置,但是當'recognitionObject.onresult'被觸發'self.onbroadcast' ===未定義。 – millarnui

+0

@BekimBacaj:不,它不是。這是一個全局變量('window.self'),是的,但沒有保留。 – Bergi