首页 > 如何访问对象内部的函数

如何访问对象内部的函数

如下, 如何在fedLib的外部访问到testConsole? http://jsfiddle.net/fPfNB/
麻烦各位大神解答下,谢谢。

var fedLib = {
    test: function (){
        function testConsole(){
            console.log('1111');
        }       
    }
}

如果是只是要在外部能访问到,方式不是很多么...如 @52lidan 的回答,再比如:

var fedLib = {
    test: function (){
        //1. this.testConsole = testConsole
        //2. fedLib.testConsole = testConsole
        //3. window.testConsole = testConsole // 当然这种不推荐
        function testConsole(){
            console.log('1111');
        }       
    }
};
fedLib.test();
fedLib.testConsole();
testConsole();

不过事实上,如果你确实需要在外部访问 testConsole 的话,说明你的结构有问题,应该在这方面更寻方案。


var fedLib = {
    test: function (){
        return function testConsole(){
            console.log('1111');
        }       
    }
};

var testInner=fedLib.test();
testInner();


如果你指的是 testConsole 的话,应该没有优雅的方法可以访问到。

因为 testConsole 只是 fedLib.test 里的一个局部变量而已;不存在于 fedLib.test 之外的地方。

【热门文章】
【热门文章】