javascript - 如何访问对象内部的函数
黄舟
黄舟 2017-04-10 13:09:44
[JavaScript讨论组]

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

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

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
PHPz
var fedLib = {
    test: function (){
        return function testConsole(){
            console.log('1111');
        }       
    }
};

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

PHP中文网

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

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

阿神

如果是只是要在外部能访问到,方式不是很多么...如 @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 的话,说明你的结构有问题,应该在这方面更寻方案。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号