使用browserify创建一个通用函数

时间:2015-10-19 22:21:33

标签: javascript browserify

我对Browserify很新,我不仅仅是在不同文件中使用的功能。我重构我的代码以在单个文件中提取此函数,因此我必须为这些函数维护此源。 这些功能已经在我的其他文件中使用,所以我不想改变我调用它们的方式,所以如果我以这种方式使用函数

var x= foo();

不想将消费者javascript改为

var x= lib.foo();

我创建了一个文件" ./ lib / common.js"

module.exports.trump = function (str, pattern) {
      var trumped = "";  // default return for invalid string and pattern

      if (str && str.length) {
        trumped = str;
        if (pattern && pattern.length) {
          var idx = str.indexOf(pattern);

          if (idx != -1) {
            trumped = str.substring(0, idx);
          }
        }
      }
      return (trumped);
        }

module.export.foo = function(options){
  return 1;
}

在我的app.js中我有:

require('./lib/common.js')
trump(ui.item.PlaceId, "-sky" )

浏览我的app.js文件后(没有错误)我在浏览器应用程序中使用它,但我得到Uncaught ReferenceError: trump is not defined

我应该如何使用单个common.js文件导出我的函数,以便在简单地调用foo();时使其工作?

1 个答案:

答案 0 :(得分:1)

在要求你的图书馆之后:

var common = require('./lib/common.js');

您可以使用以下内容将其合并到this

  1. jQuery extend()

    $.extend(this, common);
    
  2. Underscore.js extend()

    _.extend(this, common);
    
  3. Object.assign() - ECMAScript 2015(ES6)标准 - 检查浏览器兼容性

    Object.assign(this, common)
    
  4. Object.assign polyfill(来自https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign):

    if (!Object.assign) {
        Object.defineProperty(Object, 'assign', {
            enumerable: false,
            configurable: true,
            writable: true,
            value: function(target) {
                'use strict';
                if (target === undefined || target === null) {
                    throw new TypeError('Cannot convert first argument to object');
                }
    
                var to = Object(target);
                for (var i = 1; i < arguments.length; i++) {
                    var nextSource = arguments[i];
                    if (nextSource === undefined || nextSource === null) {
                        continue;
                    }
                    nextSource = Object(nextSource);
    
                    var keysArray = Object.keys(nextSource);
                    for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                        var nextKey = keysArray[nextIndex];
                        var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                        if (desc !== undefined && desc.enumerable) {
                            to[nextKey] = nextSource[nextKey];
                        }
                    }
                }
                return to;
            }
        });
    }