我们如何使用nodeJS中的module.exports返回函数?

时间:2016-03-04 08:07:19

标签: javascript node.js

我们如何使用nodeJS中的module.exports返回函数?

file_1 book.js

  module.exports = function() {
    var points = 0;
    return {
        rate: function(value) {
            points = value;
        },
        get: function() {
            return points;
        }
    }
}
  

book.js是根文件。
  我们创建了两个不同的实例   但是无法将root的方法提供给script.js文件。

file_2 main.js

  var bA = require('./book.js');
  var bB = require('./book.js');
  bB.rate(10);
  bB.get();

输出=> can not find rate and get method.

4 个答案:

答案 0 :(得分:6)

因为该函数返回一个引用了get()函数的对象,所以你需要使用 var book = require('./book.js')(); book.rate(10); book.get(); on require执行它,如下所示:

//////////////////////class MyObject
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace APP
{
    public class MyObject
    {
        public MyObject()
        {}

        private object _Value;
        public object Value
        {
            get { return _Value; }
            set { _Value = value; }
        }
    }
}

//////////////class MyDataSourceWrapper
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace APP
{
    class MyDataSourceWrapper : ITypedList, IList
    {
        private readonly string _DisplayMember;
        public readonly IList NestedList;
        public ITypedList NestedTypedList { get { return (ITypedList)NestedList; } }
        public MyDataSourceWrapper(ITypedList list, MyObject nullObject, string valueMember, string displayMember)
        {
            _ValueMember = valueMember;
            _DisplayMember = displayMember;
            _NullObject = nullObject;
            this.NestedList = (IList)list;
        }

        private MyObject _NullObject;
        private readonly string _ValueMember;
        public MyObject NullObject
        {
            get { return _NullObject; }
            set { _NullObject = value; }
        }

        class EmptyObjectPropertyDescriptor : PropertyDescriptor
        {
            private readonly string _DisplayMember;
            public readonly PropertyDescriptor NestedDescriptor;
            public readonly MyObject NullObject;
            private readonly string _ValueMember;
            public EmptyObjectPropertyDescriptor
                (PropertyDescriptor nestedDescriptor, MyObject nullObject, string valueMember, string displayMember)
                : base(nestedDescriptor.Name, (Attribute[])new ArrayList(nestedDescriptor.Attributes).ToArray(typeof(Attribute)))
            {
                _DisplayMember = displayMember;
                _ValueMember = valueMember;
                this.NestedDescriptor = nestedDescriptor;
                this.NullObject = nullObject;
            }
            public override bool CanResetValue(object component)
            {
                return false;
            }
            public override Type ComponentType
            {
                get { return typeof(object); }
            }
            public override object GetValue(object component)
            {
                if (component == NullObject)
                {
                    if (NestedDescriptor.Name == _ValueMember)
                        return NullObject.Value;
                    else if (NestedDescriptor.Name == _DisplayMember)
                        return NullObject.Value;
                    return null;
                }
                else
                    return NestedDescriptor.GetValue(component);
            }
            public override bool IsReadOnly
            {
                get { return true; }
            }
            public override Type PropertyType
            {
                get { return NestedDescriptor.PropertyType; }
            }
            public override void ResetValue(object component)
            {
                throw new NotSupportedException("The method or operation is not implemented.");
            }
            public override void SetValue(object component, object value)
            {
                throw new NotSupportedException("The method or operation is not implemented.");
            }
            public override bool ShouldSerializeValue(object component)
            {
                return true;
            }
        }
        public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
        {
            List<PropertyDescriptor> result = new List<PropertyDescriptor>();
            foreach (PropertyDescriptor pd in NestedTypedList.GetItemProperties(ExtractOriginalDescriptors(listAccessors)))
            {
                object nullVal = null;
                if (pd.PropertyType == typeof(string))
                    nullVal = "[empty]";
                result.Add(new EmptyObjectPropertyDescriptor(pd, NullObject, _ValueMember, _DisplayMember));
            }
            return new PropertyDescriptorCollection(result.ToArray());
        }
        public string GetListName(PropertyDescriptor[] listAccessors)
        {
            return NestedTypedList.GetListName(ExtractOriginalDescriptors(listAccessors));
        }

        protected static PropertyDescriptor[] ExtractOriginalDescriptors(PropertyDescriptor[] listAccessors)
        {
            if (listAccessors == null)
                return null;
            PropertyDescriptor[] convertedDescriptors = new PropertyDescriptor[listAccessors.Length];
            for (int i = 0; i < convertedDescriptors.Length; ++i)
            {
                PropertyDescriptor d = listAccessors[i];
                EmptyObjectPropertyDescriptor c = d as EmptyObjectPropertyDescriptor;
                if (c != null)
                    convertedDescriptors[i] = c.NestedDescriptor;
                else
                    convertedDescriptors[i] = d;
            }
            return convertedDescriptors;
        }
        public int Add(object value)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public void Clear()
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public bool Contains(object value)
        {
            if (value == NullObject)
                return true;
            return NestedList.Contains(value);
        }
        public int IndexOf(object value)
        {
            if (value == NullObject)
                return 0;
            int nres = NestedList.IndexOf(value);
            if (nres < 0)
                return nres;
            return nres + 1;
        }
        public void Insert(int index, object value)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public bool IsFixedSize
        {
            get { return true; }
        }
        public bool IsReadOnly
        {
            get { return true; }
        }
        public void Remove(object value)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public void RemoveAt(int index)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public object this[int index]
        {
            get
            {
                if (index == 0)
                    return NullObject;
                else
                    return NestedList[index - 1];
            }
            set
            {
                throw new NotSupportedException("The method or operation is not implemented.");
            }
        }
        public void CopyTo(Array array, int index)
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
        public int Count
        {
            get { return NestedList.Count + 1; }
        }
        public bool IsSynchronized
        {
            get { return false; }
        }
        public object SyncRoot
        {
            get { return NestedList.SyncRoot; }
        }
        public IEnumerator GetEnumerator()
        {
            throw new NotSupportedException("The method or operation is not implemented.");
        }
    }
}

//////////////////class MyGridLookupDataSourceHelper
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using System.Collections;

using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraLayout;
using DevExpress.Utils;

namespace APP
{
    public class MyGridLookupDataSourceHelper
    {

        MyObject _MyObject = new MyObject();
        private MyDataSourceWrapper _DataSourceWrapper;
        GridLookUpEdit edit;
        bool popupOpened = false;
        public MyGridLookupDataSourceHelper(GridLookUpEdit edit, ITypedList dataSource, string displayMember, string valueMember)
        {
            this.edit = edit;
            _DataSourceWrapper = new MyDataSourceWrapper(dataSource, _MyObject, valueMember, displayMember);
            edit.Properties.DisplayMember = displayMember;
            edit.Properties.ValueMember = valueMember;
            edit.Properties.DataSource = _DataSourceWrapper;
            edit.Properties.View.CustomRowFilter += View_CustomRowFilter;
            edit.ProcessNewValue += edit_ProcessNewValue;
            edit.Properties.View.RefreshData();
            edit.Properties.QueryPopUp += new CancelEventHandler(Properties_QueryPopUp);
        }

        void Properties_QueryPopUp(object sender, CancelEventArgs e)
        {
            this.popupOpened = true;
            edit.Properties.View.DataController.DoRefresh();
        }

        public static void SetupGridLookUpEdit(GridLookUpEdit edit, ITypedList dataSource, string displayMember, string valueMember)
        {
            new MyGridLookupDataSourceHelper(edit, dataSource, displayMember, valueMember);
        }

        void View_CustomRowFilter(object sender, DevExpress.XtraGrid.Views.Base.RowFilterEventArgs e)
        {
            if (!popupOpened) return;
            if (_DataSourceWrapper[e.ListSourceRow] is MyObject)
            {
                e.Visible = false;
                e.Handled = true;
            }
        }

        void edit_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            _MyObject.Value = e.DisplayValue;
            this.popupOpened = false;
            edit.Properties.View.DataController.DoRefresh();
            e.Handled = true;
        }
    }
}

/////////////////////////code used in Main
   GridLookUpEdit glue = new GridLookUpEdit();
            glue.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            MyGridLookupDataSourceHelper.SetupGridLookUpEdit(glue, GetMaterialyDataView(), "Kod", "Kod");
            eePozycje.gvView.Columns[KolNazwa].ColumnEdit = glue.Properties;

答案 1 :(得分:0)

您正在返回一个返回对象的函数。

调用该函数并获取对象

  /*file_2 main.js*/
  var bA = require('./book.js')();
  var bB = require('./book.js')();
  bB.rate(10);
  bB.get();

答案 2 :(得分:0)

以防万一某人面临与我相同的问题 我的代码有问题。最近意识到我正在进行一些API调用,因此return从API端点获取值之前返回了一个对象

我在函数调用之前添加了异步,并且它起作用了!

var util=require('./app/Utils')

const url=await util.getInfo();

答案 3 :(得分:-1)

您还可以为匿名导出功能提供名称

module.exports.myfun = function() {
var points = 0;
return {
    rate: function(value) {
        points = value;
    },
    get: function() {
        return points;
    }
} }

然后在另一个文件中使用该功能

var inc = require('./comp.js');
var mod = inc.myfun();
mod.rate(10);
console.log(mod.get());

通过这种方式,您可以在需要时使用'()',但也可以使用该选项