如何使用javascript正确返回对象而不是函数?

时间:2015-06-29 13:08:49

标签: javascript

我正在为自己制作一个帮助库。首先,我这样包装:

(function (Helper, window, document) {
    var Helper = Helper || {};
    var type = function () {
        return {
            isObject: function (value) {
                return value !== null && Object.prototype.toString.call(value) === "[object Object]";
            },
            isNumber: function (value) {
                return value !== null && Object.prototype.toString.call(value) === "[object Number]" && !isNaN(value);
            },
            isString: function (value) {
                return value !== null && Object.prototype.toString.call(value) === "[object String]";
            },
            isArray: function (value) {
                return value instanceof Array;
            },
            isFunction: function (value) {
                return typeof value === "function";
            },
            isDate: function (value) {
                return value instanceof(Date);
            },
            isRegExp: function (value) {
                return value instanceof RegExp;
            },
            isBoolean: function (value) {
                return value !== null && Object.prototype.toString.call(value) === "[object Boolean]";
            },
            isError: function (value) {
                return value instanceof Error;
            },
            isNull: function (value) {
                return value === null;
            },
            isUndefined: function (value) {
                return typeof value === "undefined";
            }
        };
    };
    Helper.type = type;
})(Helper = window.helper || {}, window, document);

现在这很好用,但为了实现这些功能,我需要调用一个像Helper.type()。isNumber(5)这样的函数。它应该如何看起来它将作为对象值返回,比如这个Helper.type.isNumber(5)?

3 个答案:

答案 0 :(得分:0)

只需从function()

中删除type包装
(function (Helper, window, document) {
    var Helper = Helper || {};
    var type = {
        isObject: function (value) {
            return value !== null && Object.prototype.toString.call(value) === "[object Object]";
        },
        ...
        isUndefined: function (value) {
            return typeof value === "undefined";
        }
    };
    Helper.type = type;
})(Helper = window.helper || {}, window, document);

答案 1 :(得分:0)

只需删除function type(){}; Helper.type = type;,然后将return替换为Helper.type =

(function(Helper, window, document) {

  Helper.type = {
    isNumber: function () {...}
  };


 })(Helper = window.helper || {}, window, document);

答案 2 :(得分:0)

而不是分配函数引用:

Helper.type = type;

改为指定函数返回值:

Helper.type = type();