是否可以在JavaScript函数中定义全局变量?
我想在其他函数中使用trailimage变量(在makeObj函数中声明).
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
**var trailimage = [address, 50, 50];**
document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0" style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
obj_selected = 1;
}
function truebody() {
return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? …Run Code Online (Sandbox Code Playgroud) 例如,我想使用自定义记录器:
logger = require('basic-logger'),
logger.setLevel('info')
var customConfig = {
showMillis: true,
showTimestamp: true
}
var log = new logger(customConfig)
Run Code Online (Sandbox Code Playgroud)
如何在其他模块中使用此记录器而不是console.log?
在我的server.js中,我包含了下划线库.
var _ = require('underscore')
Run Code Online (Sandbox Code Playgroud)
我的路线是这样的:
// require routes
require('./routes/document');
Run Code Online (Sandbox Code Playgroud)
在文档路径中,我想使用下划线.但似乎_ var不是继承/在文档范围内.这是否意味着我必须在每个必需的路线上设置_ var?或者有更聪明的方法来做到这一点?
谢谢.
如何在nightwatch.js中创建一个全局可访问的变量?我正在使用变量来存储自定义网址(取决于我们的在线产品中加载了哪个商店),但我需要它可以通过多个javascript函数访问.看起来它的值在每个函数结束后重置,尽管它被声明在文件头部的函数之外.
我找不到如何在 Javascript 中删除代码重复(基本上是我在 Java 中使用基类实现的)。
具体示例是(至少)以下代码,它对所有规范文件(以及潜在的页面对象,因为我正在量角器中使用该模式进行测试)都是通用的:
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var expect = chai.expect;
Run Code Online (Sandbox Code Playgroud)
我可以做一些有希望随处可得?我尝试在量角器配置中在规范之前加载一个文件:
specs: [
'e2e/helpers/commonDefinitions.js',
'e2e/**/*.spec.js'
]
Run Code Online (Sandbox Code Playgroud)
或使用beforeLaunch或onPrepare(但想要一个函数,不确定如何以这种方式公开变量),但没有成功。
但是,对于这种代码重用,我更喜欢通用的 Javascript 方法。
有什么好的方法可以避免在任何地方重复这种常见的代码,尤其是在测试中(mocha、karma、protractor)?
我在nodejs中有一个应用程序.在其中,我定义了一些跨多个文件共享的全局变量.例如:
//common.js
async = requires("async");
isAuthenticated = function() {
//...
return false;
};
//run.js
require("common.js");
async.series([function () {
isAuthenicated();
}], function () {
console.log("done");
});
Run Code Online (Sandbox Code Playgroud)
我希望将变量async和isAuthenticated变量缩小,但在所有文件中缩小为相同的东西.它看起来如下:
//common.min.js
a = requires("async");
b = function() {
//...
return false;
};
//run.min.js
require("common.js");
a.series([function () {
b();
}], function () {
console.log("done");
});
Run Code Online (Sandbox Code Playgroud)
如何在uglifyjs中做到这一点?
我正在循环遍历文件并uglifyjs $file -m "sort,toplevel" -c > $file.min在每个文件上使用命令.
我需要一种在动态文件中调用变量的方法,在前端,如果在函数外部创建变量,则将其放在窗口对象上,然后可以使用
window['nameOfVar']
Run Code Online (Sandbox Code Playgroud)
我试图用它而不是nodejs中的窗口来做到这一点,但我什么也没有。
window['nameOfVar']
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这种行为
javascript ×6
node.js ×4
base-class ×1
code-reuse ×1
declaration ×1
function ×1
require ×1
scope ×1
testing ×1
uglifyjs2 ×1
variables ×1