我希望能够在创建新的onbroadcast
对象后在SpeechRecognition
中设置函数SpeechRecognition
,以便在满足某些条件时可以在内部调用此函数。
我希望能够像设置onerror
webkitSpeechRecognition
中的内容一样设置它。当我在开发人员工具中查看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 :(得分:0)
您需要将onbroadcast
称为您实例的property(this.onbroadcast
)。它并没有神奇地在构造函数范围内作为变量可用。
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();
}