vvo / chainit

Turn an asynchronous JavaScript api into an asynchronous chainable JavaScript api
Other
12 stars 4 forks source link

new Function(functionBody) gets a function while expection a string. #10

Closed simoami closed 10 years ago

simoami commented 10 years ago

index.js: Line 82

  Object.keys(Constructor)
    .forEach(function(name) {
      Chain[name] = new Function(Constructor[name]); // <- this throws an error 
    });

The error is:

SyntaxError: Unexpected token (
    at Object.Function (<anonymous>)
    at /Users/username/examples/node_modules/chainit/index.js:82

To reproduce:

var Class = function() {};
Class.prototype.test = function() {};
Class.extend = function() {};

var NewClass = chainit(Class);
christian-bromann commented 10 years ago

This function assignment:

Class.extend = function() {};

gets resolved into:

new Function(function() {
})

which doesn't work since you cannot pass anonymous function expressions as argument into new Function. To fix it just replace

Class.extend = function() {};

with

Class.extend = function extend() {};

I will implement a fix later that will handles such situations and will explain it in more detail. Thank you!

simoami commented 10 years ago

Thanks for the quick feedback!

christian-bromann commented 10 years ago

As you may know, there are two types of function expressions:

named

var func = function myFunc() {}

anonymous

var func = function() {}

But there is only one type of function declaration:

function func() {}

By passing an anonymous function expression into the function constructor the actual value of the parameter within the constructor would be

function() {}

which is neither a function expression nor a function declaration. It's just a syntax error. I don't know why chainit has assigned static functions to the chain via new Function before, but I removed it and just assigning the actual value now. I added some tests to make sure that static and prototype function get chained properly.

fixed and published (v2.1.0)