如何从其他JavaScript的一个JavaScript中调用函数

时间:2015-04-18 03:00:57

标签: javascript android cordova phonegap-plugins

我必须从signal.js java脚本文件访问index.html中的cellid,cellid在signal.js文件中定义。目前我在index.html中使用require函数来获取信号对象,但这不起作用

**index.html**

<!DOCTYPE html>
<html>
  <head>  
  <script type="text/javascript" charset="utf-8" src="signal.js"></script>
  <script type="text/javascript" charset="utf-8">
    var signal = require ("signal");
    alert("CellID : "+  signal.cellID);
    var CellID = signal.cellID;
  </script>
  </head>
</html>

signal.js

var exec = require('cordova/exec'),
    cordova = require('cordova');

var Signal = function() {
    this.imei = null;
    this.operator = null;
    this.cellID = null;
    this.lac = null;
    this.neighbors = {};
    // Create new event handlers on the window (returns a channel instance)
    this.channels = {
        watchingnetwork: cordova.addWindowEventHandler("watchingnetwork")
    };
    for (var key in this.channels) {
        this.channels[key].onHasSubscribersChange = Signal.onHasSubscribersChange;
    }

};

Signal.onHasSubscribersChange = function() {
    exec(signal.status, signal.error, "Signal", "getSignalInfo", []);
}

/**
 * Callback for signal initiated
 *
 * @param {Object} info            keys: imei, isPlugged
 */
Signal.prototype.status = function(info) {
    cordova.fireWindowEvent("watchingnetwork", info);
    if (info) {
        if (signal.imei !== info.imei || signal.operator !== info.operator) {

            if (info.imei == null && signal.imei != null) {
                return; // special case where callback is called because we stopped listening to the native side.
            }

            // Something changed. Fire watching network event

            signal.imei = info.imei;
            signal.operator = info.operator;
            signal.cellID = info.cellID;
            signal.lac = info.lac;
            signal.neighbors = info.neighbors;
        }
    }
};

/**
 * Error callback for signal initiated
 */
Signal.prototype.error = function(e) {
    console.log("Error initializing advanced network plugin: " + e);
};

var signal = new Signal();

module.exports = signal;

我该怎么做??

2 个答案:

答案 0 :(得分:2)

signal.js成为第一,

<script src="signal.js"></script>
<script>
    // Your code here
</script>

然后第二个<script>可以使用signal.js中定义的任何内容。

答案 1 :(得分:0)

实际上,如果你想使用函数Signal

// signal.js
var Signal = function() {

    // ....
};

// use function Signal 
Signal();

如果你想使用Signal(),你必须留在范围内。

所以......

<script src="signal.js"></script>
<script>
    // some code ...
</script>

上面的代码意味着将signal.js文件中的代码和一些代码放入一个范围。当你包含js文件:signal.js时,就像:

<script>
var Signal = function() {

    // ....
};

// some code ...
Signal()
<script>

将代码包含在一个范围内