当用匿名函数括起一个对象时,显示错误消息

When enclose an object by anonymous function, show me error message

本文关键字:显示 错误 消息 一个对象 函数      更新时间:2023-09-26

我有以下简单的例子:

(function() { 
var note = {
   show: function() {
        alert('hi');
    }
 };
})();

时使用

note.show();

Show me error message ReferenceError: note is not defined。但是,当使用note对象而不使用匿名函数时,可以正常工作。

现在,我如何在匿名函数之外或在其他页面中使用notes对象?

我相信您的意思是使用类似模块模式的东西。一个非常基本的例子是:

var note = (function() { 
 return {
   show: function() {
        alert('hi');
    }
 };
}());

这只在内部有闭包时有用,比如:

var note = (function() { 
   var someNumber = 10;
   return {
      show: function() {
         alert('hi');
      },
      someNumberTimes(n) {
         return someNumber * n;
      }
   };
}());
console.log(note.someNumberTimes(5)); // 50