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

时间:2016-06-15 22:52:09

标签: javascript javascript-objects

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

1 个答案:

答案 0 :(得分:0)

您需要将onbroadcast称为您实例的propertythis.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();
}