我有 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/