javascript - 在javascript中访问对象方法

标签 javascript jquery

我有 js 文件 myScript.js

(function () {    
    'use strict';    
    if (!window.myObj) {
        window.myObj= {};
    }    
    var myObj= window.myObj;
    myObj = {
       home: function () {
          console.log('hi from home');
       }, 
       details: function(){
          console.log('hi from details');
       }    
})();

内部 View 页面我正在尝试访问 myObj 对象上的 home 方法

<script>
        $(document).ready(function () {
            myObj.home();
        });
</script>

但是我得到了

uncaught TypeError: myObj.home is not a function(…)

myScript.js 已加载,加载页面上没有控制台错误。

最佳答案

您可以直接将属性分配给 myObj,而无需覆盖变量并保留 window.myObj

赋值前

                    +----------------+
window.myObj -----> |                |
                    |  { }           |
myObj ------------> |                |
                    +----------------+

分配后

                    +----------------+
window.myObj -----> |  { }           |
                    +----------------+

                    +----------------+
myObj ------------> | {              |
                    |  home: fn ..,  |
                    |  details: fn ..| 
                    | }              |
                    +----------------+

(function () {    
    'use strict';    
    if (!window.myObj) {
        window.myObj = {};
    }    
    var myObj = window.myObj;
    myObj.home = function () {
        console.log('hi from home');
    }; 
    myObj.details = function(){
        console.log('hi from details');
    };
})();

myObj.home();
myObj.details();

或者使用Object.assign在 ES6 中

(function () {    
    'use strict';    
    if (!window.myObj) {
        window.myObj = {};
    }    
    var myObj = window.myObj;
    Object.assign(myObj, {
        home: function () {
            console.log('hi from home');
        },
        details: function(){
            console.log('hi from details');
        }
    });
})();

myObj.home();
myObj.details();

关于javascript - 在javascript中访问对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330227/

相关文章:

javascript - Selenium Webdriver - 仅具有精确值标识的元素,js/html

jquery - 在 Jquery Mobile 中修复页脚

javascript - 如何在数组中随机选择随机数量的项目

php - 没有选择正确的行进行编辑

javascript - 谷歌翻译字体标签

javascript - 如何将附加参数传递给 graffle.js

javascript - Laravel 多页面 View 和 session

javascript - 在异步循环中设置 useState Hook

javascript - 从方法更新对象属性

javascript - 使用 jQuery 陷入延迟状态