簡體   English   中英

如何將一個JavaScript文件中的變量訪問/獲取到另一個JavaScript文件中

[英]how to access/get the variable in one javascript file to another javascript file

如何從一個javascript文件訪問/獲取變量到另一個javascript文件。 像first.js包含如下函數first.js。

this.first = function(){
    var x = ['new','old'] 
}

現在,我想訪問另一個文件中的“ x”,例如我嘗試過的second.js

var first = require('../first.js');  //path to the first.js file
console.log(first.x)

但獲得未定義的值。 我想從first.js獲取/訪問“ x”,我正在使用它來使用頁面對象進行量角器E2E測試。

函數/變量在哪個js文件上都沒有關系。 解析后,它們都屬於同一個window

訪問x屬性時會得到undefined ,因為它是私有的。 x僅存在於first函數的本地范圍內。

這是一個如何訪問x的示例。

var first = (function () {
    // private variables / functions
    var x = ['new', 'old'];

    // public properties (properties of "first")
    return {
        getX: function () {
            return x; // x.slice(0); if you want to send a copy of the array
        }
    }
}());

node.js中的模塊加載系統要求您使用module.exports公開要共享的數據類型:

您的示例將被重寫如下:

// first.js

module.exports = {
   x : 'Something here',
   y : 'another item'
};

然后在另一個文件上

var first = require('../first.js');  //path to the first.js file
console.log(first.x)

查看有關Node.js模塊加載系統的更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM