Skip to content
This repository has been archived by the owner on Sep 10, 2023. It is now read-only.

Commit

Permalink
fix: fix new Function and add test case
Browse files Browse the repository at this point in the history
  • Loading branch information
axetroy committed Mar 13, 2018
1 parent ed26415 commit c7cf98e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
9 changes: 6 additions & 3 deletions src/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ const visitors: EvaluateMap = {
scope.$var(functionName, generatorFunc);
} else {
const func = visitors.FunctionExpression(path.$child(node as any));

Object.defineProperties(func, {
length: { value: node.params.length },
name: { value: functionName }
Expand Down Expand Up @@ -906,9 +907,11 @@ const visitors: EvaluateMap = {
NewExpression(path) {
const { node } = path;
const func = evaluate(path.$child(node.callee));
Object.defineProperty(func, "length", { value: node.arguments.length });
const args = node.arguments.map(arg => evaluate(path.$child(arg)));
return new (func.bind.apply(func, [null].concat(args)))();
const args: any[] = node.arguments.map(arg => evaluate(path.$child(arg)));
const entity = new func(...args);
entity.prototype = entity.prototype || {};
entity.prototype.constructor = func;
return entity;
},

// ES2015
Expand Down
20 changes: 14 additions & 6 deletions test/ecma5/new/NewExpression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,26 @@ import vm from "../../../src/vm";
test("NewExpression", t => {
const sandbox: any = vm.createContext({});

const output: any = vm.runInContext(
const { people, People }: any = vm.runInContext(
`
function People(name){
function People(name, age){
this.name = name;
}
module.exports = new People("axetroy");
module.exports.People = People;
module.exports = {
people: new People("axetroy", 12),
People: People
};
`,
sandbox
);

t.deepEqual(output.People.length, 1);
t.deepEqual(output.name, "axetroy");
// constructor
t.deepEqual(People.length, 2);
t.deepEqual(People.name, "People");

// entity
t.true(people instanceof People);
t.deepEqual(people.name, "axetroy");
t.true(people.prototype.constructor === People);
});

0 comments on commit c7cf98e

Please sign in to comment.