Skip to content

生成的function.length不正确 #1

@axetroy

Description

@axetroy

例如运行这段代码:

function test(name){
  return "hello " + name;
}

console.log(test.length); // 正常情况下,应该是1, 但实际上是0

module.exports = test;

查看了相关源码,在下面的:

FunctionExpression: (node: ESTree.FunctionExpression, scope: Scope) => {

    FunctionExpression: (node: ESTree.FunctionExpression, scope: Scope) => { 
        return function (...args) {
            const new_scope = new Scope('function', scope)
            new_scope.invasived = true
            for (let i = 0; i < node.params.length; i++) {
                const { name } = <ESTree.Identifier>node.params[i]
                new_scope.$const(name, args[i])
            }
            new_scope.$const('this', this)
            new_scope.$const('arguments', arguments)
            const result = evaluate(node.body, new_scope)
            if (result === RETURN_SINGAL) {
                return result.result
            }
        }
    },

这里Return的function,使用的是 function (...args),导致它的length属性不确定..

可以这么改

    FunctionExpression: (node: ESTree.FunctionExpression, scope: Scope) => { 
        const func function (...args) {
            const new_scope = new Scope('function', scope)
            new_scope.invasived = true
            for (let i = 0; i < node.params.length; i++) {
                const { name } = <ESTree.Identifier>node.params[i]
                new_scope.$const(name, args[i])
            }
            new_scope.$const('this', this)
            new_scope.$const('arguments', arguments)
            const result = evaluate(node.body, new_scope)
            if (result === RETURN_SINGAL) {
                return result.result
            }
        }

        // 手动矫正length
        Object.defineProperty(func, "length", {value: node.params.length});

        return func;
    },

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions