如何检查对象内部是否存在私有(private)函数?
var myObj = function(){
var myFunc = function(){};
var init = function(){
//has myFunc been defined?
}
}
我知道我可以做到这一点:
if (typeof myFunc == 'function') {
//myFunc exist
}
但这正在检查全局范围。
如何将其限制在我的对象范围内?
这是我需要的最简单的情况:
var myComponent = function () {
var exportExcel = function () {
};
this.export = function (type) {
if('export'+type is a private function in this scope){
window["export"+type]()//but in local scope;
}
}
};
这是我现在的工作:
var myComponent = function () {
var Exports = {
Excel: function () {
}
};
this.export = function (type) {
if (Exports.hasOwnProperty(type)) {
Exports[type]();
} else {
alert('This Export type has not been implemented Yet ! or it never will ... how knows? well i don\'t ...');
}
}
};
最佳答案
正如您可能注意到的:
function myFunc () {};
function myObj () {
function init () {
if (myFunc) // passes
};
}
你可以作弊一点:-|
function myObj () {
var isdef = { myFunc: true };
function myFunc () {};
function init () {
if (isdef.myFunc) // do something
};
}
我想知道为什么有人会这样做。
关于javascript - 检查 JavaScript 中的对象内部是否存在私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702475/