【问题标题】:Why is this constructor (using "new Function") breaking?为什么这个构造函数(使用“新函数”)会破坏?
【发布时间】:2018-02-18 00:54:52
【问题描述】:

我是 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?"

*/

提前致谢!

【问题讨论】:

  • 真的没有理由从这样的字符串构建函数。
  • 我的意思是我也认为这很不合理,但他们在课堂上就是这样教的
  • 你应该投诉。通常,实际的专业程序员会一致反对这种方法。
  • @Pointy 很高兴知道!!谢谢你:)

标签: javascript templates constructor frameworks


【解决方案1】:

不使用new 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);
        }
    };

}

【讨论】:

  • 嗯,成功了——谢谢!根据我自己的理解,使用 new Function 构造函数有什么好处吗?还是在某些情况下使用 is 更好?该课程让我们专门使用它(new Function),但这更容易(而且更干净!)
  • @Zach 仅在极少数情况下才需要从源代码字符串构建代码。
猜你喜欢
  • 2013-02-03
  • 2015-10-12
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多