Question

I'm trying to use the object I've expose from the a javascript file using browserify, but I keep getting error Uncaught TypeError: undefined is not a function

Here is an example:

foo.js:

var foo = function() {
  this.f1 = function(){
    console.log('function1')
  }
  this.f2 = function(){
    console.log('function2')
  }
};

module.exports = foo;

I'm trying to use the foo in the index.html.

after enter command: browserify foo.js > bundle.js

and include bundle.js to html file.

index.html:

<html>
  <head>
    <script src="./bundle.js"></script>
    <script>
      var foo = new foo();  // Uncaught TypeError: undefined is not a function

      foo.f1();
    </script>
  </head>

  <body>

  </body>
</html>

What am I doing wrong with browserify? Thanks in advance.


EDIT: for wrong example.

original wrong example

foo.js:

var foo = {
  f1: function(){
    console.log('function1')
  },
  f2: function(){
    console.log('function2')
  }
};

module.exports = foo;
Was it helpful?

Solution 3

browserify foo.js --standalone foo > bundle.js

OTHER TIPS

If you want to use new, you should declare the foo class like:

foo = function() {
  this.f1 = function(){
    console.log('function1')
  };
  this.f2 = function(){
    console.log('function2')
  };
};

foo_obj = new foo();
foo_obj.f1();
foo_obj.f2();

Instead of a literal. Otherwise, simply the methods of the foo object.

var foo = {
  f1: function(){
    console.log('function1')
  },
  f2: function(){
    console.log('function2')
  }
};

foo.f1();
foo.f2();

Update:

Let's see, I've never used browserify, but accordingly to their docs, you should do something like:

foo.js

module.exports = function() {
  this.f1 = function(){
    console.log('function1')
  },
  this.f2 = function(){
    console.log('function2')
  }
};

main.js

var foo = require('foo');

Then, do:

browserify main.js -o bundle.js

And finally import bundle.js and use new foo() to create the object inside your script.

You're trying to instantiate an object as if it was a function, e.g.

new {}; // invalid!!
new function() {}; // valid!

I would recommend you use either

exports.foo1 = function() { console.log('foo'); }
exports.bar1 = function() { console.log('bar'); }

or if you really want to keep new foo() use:

module.exports = foo;
function foo() {
    this.foo1 = function() { console.log('foo'); }
    this.bar1 = function() { console.log('bar'); }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top