在外部设置一个可以在内部调用的对象函数

Set an object function externally that can be called internally

我希望能够在创建新的 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;
}

您需要将 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();
}