gpt4 book ai didi

javascript - 在类范围之外触发​​事件 javascript

转载 作者:行者123 更新时间:2023-12-03 04:19:41 25 4
gpt4 key购买 nike

我有课:

var psTesting = (function(){

var privatevariable;

function setVariable(value){
privatevariable = value;
console.log('the variable value is ' + value);
}

function dismiss ( callback ) {
console.log('entro dismiss')
if( callback ) callback();
if( this.onDismiss ) this.onDismiss();
}

return {
pVariable : function(val) {
setVariable(val)
}
}
})();

psTesting.pVariable(22);

psTesting.onDismiss = function(){
console.log('this is a onDismiss test');
}

我希望能够从类外部触发 onDismiss 函数 psTesting.onDismiss()

我一直在尝试使用 .call .apply .bind 东西,但没有运气。

谢谢,PA

最佳答案

在内部保存对您要返回的对象的引用,以便您可以使用它来访问添加到该对象的 .onDismiss()

var psTesting = (function() {

var privatevariable;

var obj = {
pVariable: function(val) {
setVariable(val)
}
}

function setVariable(value) {
privatevariable = value;
console.log('the variable value is ' + value);
}

function dismiss(callback) {
console.log('entro dismiss')
if (callback) callback();
if (obj.onDismiss) obj.onDismiss();
}

return obj;
})();

psTesting.pVariable(22);

psTesting.onDismiss = function() {
console.log('this is a onDismiss test');
}

关于javascript - 在类范围之外触发​​事件 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44003827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com