user1765862 user1765862 - 1 month ago 5
jQuery Question

accessing object method in javascript

I have js file 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');
}
})();


inside view page I'm trying to access home method on myObj object

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


but I'm getting


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


myScript.js is loaded and no console error on loading page.

Answer

You could assign directly the properties to myObj without overwriting the variable and keeping window.myObj.

Before assignment

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

after assignment

                    +----------------+
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();

Or use Object.assign in 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();

Comments