为什么这个构造函数(使用“new Function”)破坏了?

时间:2018-02-18 00:54:52

标签: javascript templates constructor frameworks

我是JS的新手,我正在尝试构建一个模板函数(在MOOC中赋值),它基本上返回一个函数,该函数根据输入字符串和分隔符返回渲染模板。

无论如何,这是我到目前为止的代码,我不知道为什么它会破坏..我真的尝试过我能想到的一切!

var template = function(stringToParse, options) {

    // find out if custom delimiters are being used
    if (typeof options != 'undefined') {
        var openDelim = options.open;
        var closeDelim = options.close;
    } else {
        var openDelim = '*(';
        var closeDelim = ')*';
    }

    // get the length of the closing delim for parsing later
    var delimCharLen = closeDelim.length;

    // helper function
    function parseOutFiller(_array) {

        // get an array of the indices of each closing delim in the string
        var closingDelims = [];
        for (i=0; i < _array.length; i++) {
            closingDelims.push(_array[i].indexOf(closeDelim));
        }

        // remove the filler text leading up to the closing dim in each substring
        for (i = 0; i < _array.length; i++) {
            if (closingDelims[i] > 0) {
                _array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
            }
        }

        return _array
    }

    // split array, get the closing indices, and parse out the filler text
    var splitArray = stringToParse.split(openDelim);
    var parsedString = parseOutFiller(splitArray);

    return new Function("var locParsedString = [" + parsedString + "];\
                         var inputCopy = [];\
                         for (i=0; i < arguments.length-1; i++) {\
                             inputCopy.push(arguments[i])\
                         }\
                         var templateString = '';\
                         for (i=0; i < inputCopy.length; i++) {\
                             templateString += locParsedString[i];\
                             templateString += inputCopy[i];\
                         }\
                         templateString += locParsedString[locParsedString.length-1];\
                         nRepeat = arguments[arguments.length-1];\
                         for (i=0; i < nRepeat; i++) {\
                             console.log(templateString);\
                         }"
                       )
}

然后当我运行它时......

var string = "Is <<! thing !>> healthy to <<! action !>>?";
var logResult = template(string, {open: '<<!', close: '!>>'});

logResult('this', 'eat', 3)

/*

Which should print:

"Is this healthy to eat?"
"Is this healthy to eat?"
"Is this healthy to eat?"

*/

提前致谢!

1 个答案:

答案 0 :(得分:2)

不使用新的Function(),只需使用return function(){}。 这样,就不需要在函数内部创建locParserString。您可以直接使用parsedString:

var template = function(stringToParse, options) {

    // find out if custom delimiters are being used
    if (typeof options != 'undefined') {
        var openDelim = options.open;
        var closeDelim = options.close;
    } else {
        var openDelim = '*(';
        var closeDelim = ')*';
    }

    // get the length of the closing delim for parsing later
    var delimCharLen = closeDelim.length;

    // helper function
    function parseOutFiller(_array) {

        // get an array of the indices of each closing delim in the string
        var closingDelims = [];
        for (i=0; i < _array.length; i++) {
            closingDelims.push(_array[i].indexOf(closeDelim));
        }

        // remove the filler text leading up to the closing dim in each substring
        for (i = 0; i < _array.length; i++) {
            if (closingDelims[i] > 0) {
                _array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
            }
        }

        return _array
    }

    // split array, get the closing indices, and parse out the filler text
    var splitArray = stringToParse.split(openDelim);
    var parsedString = parseOutFiller(splitArray);

    return function () {
        var inputCopy = [];
        for (i=0; i < arguments.length-1; i++) {
            inputCopy.push(arguments[i])
        }
        var templateString = '';
        for (i=0; i < inputCopy.length; i++) {
            templateString += parsedString[i];
            templateString += inputCopy[i];
        }
        templateString += parsedString[parsedString.length-1];
        nRepeat = arguments[arguments.length-1];
        for (i=0; i < nRepeat; i++) {
            console.log(templateString);
        }
    };

}