假设我有一个具有结构的 html 文件
<script>
let firstClass = new FirstClass();
var secret = 'code';
function FirstClass() {
this.init = function () {
console.log(SecondClass());
}
}
function SecondClass() {
return 'value';
}
</script>
// some html
<script>
firstClass.init(); // should return a value
console.log(secret); // should be undefined
SecondClass(); // should not be accessible
FirstClass(); // should not be accessible
</script>
我如何确保只有 firstClass.init()
可从 <script>
的第二部分获得而不是 SecondClass()
?
我想使用匿名函数,比如 ;function({})();
最佳答案
在包含 FirstClass
的 IIFE 中实例化 firstClass , SecondClass
, 和 secret
, 并且只返回 firstClass
来自 IIFE:
<script>
const firstClass = (() => {
const secret = 'secret';
function FirstClass() {
this.init = function() {
console.log(SecondClass());
}
}
function SecondClass() {
return 'value';
}
return new FirstClass;
})();
</script>
<script>
firstClass.init(); // should return a value
console.log(
typeof secret,
typeof SecondClass,
typeof FirstClass
);
</script>
注意需要使用</script>
, 不是 <scipt>
, 你需要使用 new
当调用构造函数以使用分配给 this
的属性时在构造函数中。
关于javascript - 如何使用匿名函数使某些函数和变量在 Javascript 中全局可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55969024/