您好,显然当我在该范围内创建一个函数时,它在该函数外是不可见的。有没有另一种方法可以调用 resettimeline 函数而不将其放在本地范围之外?我需要调用许多其他函数,它们在函数 ganttChart(config) 中,并且不可能仅仅为了调用它们而将它们移出该函数。
index.html
<!DOCTYPE html>
<html>
<head>
<title>Gantt Chart</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="chart" id="Chart" style="width: 100%"></div>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script type="text/javascript" src="ganttChart.js"></script>
<script type="text/javascript" src="app.js"></script>
<a id="myButton" href="javascript:void(0);" onclick="resettimeline()" >Click here</a>
<br/>
<a href="javascript:updateData()" >Update</a>
</body>
</html>
app.js
var data = [
{
id: 1,
title: "Request received",
action: 'from',
user: 'SAS',
start_date: "08/08/2016",
end_date: "10/08/2016",
value: 67,
// term: "Short Term",
completion_percentage: 29,
color: "#770051",
}
];
ganttChart(config);
ganttChart.js
function ganttChart(config) {
.
.
.
.
function resettimeline() {
document.location.reload();
};
}
最佳答案
虽然您的问题并不完全清楚,但这听起来像是 Revealing Module Pattern 的工作,这是控制 Scope 的常用方法。
原则是使用一个Immediately Invoked Function Expression (IIFE) 仅在外部作用域中公开您需要的该函数的部分。
下面的伪代码描述了原理......
/* a function calls itself */
var invokedFunction = (function() {
/* scoped (private) variables */
var someValue = 20;
var someOtherValue = 0;
/* scoped (private) method */
function _someMethod1() {
return someValue + someOtherValue;
}
/* scoped (public) method */
function someMethod2(num) {
/* some action or process */
someOtherValue += num || 1;
/* return private method1 */
return _someMethod1();
}
/* expose public method2 */
return {
method: someMethod2
};
}());
console.log( invokedFunction.method() ); // => 21
console.log( invokedFunction.method(4) ); // => 25
除了 someMethod2
函数外,invokedFunction()
的所有工作都被排除在外,该函数通过 invokedFunction
的返回暴露值(value)。
可以在这里找到进一步的解释:
- > Learning JavaScript Design Patterns, Addy Osmani
- > An Introduction to Immediately Invoked Function Expressions, Joshua Clanton
- > Closures in JavaScript, CodeProject
希望对您有所帮助:)
关于javascript - 我如何使用html链接调用外部js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623142/