javascript - 检查 JavaScript 中的对象内部是否存在私有(private)函数

标签 javascript function object private

如何检查对象内部是否存在私有(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/

相关文章:

javascript - polymer 1.x : Databinding Arrays

c# - 如何将 Dictionary<string, string> 变量从代码后面传递给 asp.net?

javascript - 为什么我不能设置 JavaScript 函数的名称属性?

java - 如何从 Java 对象/ArrayList 中排序并获取最高值

c - 将 FORTRAN 对象传递给 C,反之亦然

javascript - 台式电脑中的 html5 geoLocation 错误

JavaScript - 如何保持 for 循环直到收到函数回调

sql - PostgreSQL:为什么作为表达式的子查询不能返回多行,而函数可以?

C++ 函数指针数组错误

C# 和 Oracle,登录表单 : Operation is not valid due to the current state of the object