javascript - Javascript 私有函数辅助
问题描述
我在掌握如何将 javascript 函数/变量设为私有时遇到问题。我需要如何编辑它以使函数/变量像这样私有。
<html>
<head>
<style>
#panel, .flip {
font-size: 16px;
padding: 10px;
text-align: center;
background-color: #4CAF50;
color: white;
border: solid 1px #a6d8a8;
margin: auto;
}
#panel {
display: none;
}
</style>
</head>
<body>
<p class="flip" onclick="myFunction()">Click to show panel</p>
<div id="panel">
<p>This panel contains a div element, which is hidden by default (display: none).</p>
<p>It is styled with CSS and we use JavaScript to show it (display: block).</p>
<p>How it works: Notice that the p element with class="flip" has an onclick attribute attached to it. When the user clicks on the p element, a function called myFunction() is executed, which changes the style of the div with id="panel" from display:none (hidden) to display:block (visible).</p>
<p>You will learn more about JavaScript in our JavaScript Tutorial.</p>
</div>
<script>
function myFunction() {
document.getElementById("panel").style.display = "block";
}
</script>
</body>
</html>
解决方案
你不能。
JavaScript 没有任何访问修饰符的概念(export
在模块之外,但<script>
具有内联脚本的元素不是 JavaScript 模块)。
此外,OOP 语言中的修饰符只对/类型private
有意义,对自由函数没有意义(因为所有自由函数都是全局范围的),所以 of 的想法毫无意义。class
struct
private function myFunction() { ... }
目前在 JavaScript 生态系统中,当使用 JavaScript class
(它只是prototype
声明的语法糖)时,使用前导下划线来表示“私有”属性(包括函数)是司空见惯的——但这是一种约定,而不是一种语言特性,它也不会阻止从另一个脚本调用函数:
class Foobar {
doSomething() { // <-- "public"
// ...
}
_doSomethingElse() { // <-- the leading underscore is a hint to consumers not to use this property directly, but they can still call it if they want to.
// ...
}
}
var f = new Foobar();
f.doSomething();
f._doSomethingElse(); // <-- nothing stops a consumer from calling this function-property.
解决方法:
请注意,您可以拥有一个带有无法访问的匿名函数的 JavaScript 对象(使用class
或仅使用 POJO),前提是您可以以不暴露它们的方式将它们连接起来 - 但这种方法的缺点是您自己的代码可以t 也直接调用它们。这种方法可用于设置事件处理程序而不会污染全局命名空间:
class Foobar {
constructor() {
(function() { // This is an IIFE
const button = document.getElementById( 'foobar' );
button.addEventListener( 'click', function() {
alert("clicked!);
} );
})();
}
}
在上面的代码中,click
现在不能直接调用 IIFE 和事件处理函数,因为它们没有名称,并且在脚本运行后它们将不在范围内。
推荐阅读
- c# - 如何在 .NET 中使用其驱动程序名称查找串行端口设备?
- dotnetnuke - 自定义 FileHandler - 获取登录用户
- android - 如何使用已经绑定的设备设计 android BLE 流程?
- elasticsearch - 您可以在 Elasticsearch 中存储和检索整个文档吗?
- swift - 有序阵列闪烁效果?
- eclipse - eclipse中黄瓜测试的初始化错误
- java - 一次只允许一个用户访问数据
- python - 用 pip 安装 wxPython (Python2.7)
- python - 将 Pandas 系列(基于索引)切片成多列数据框
- c++ - libpqxx 和 cmake 找不到 -lpq