0

I am working on a url processing class and would like to access it via a constructor. For example, calling new Url("http://www.stackoverflow.com?param=value") would return different components of the url.

While I have a basic function working I am not able to use the constructor in a different file. In this case I want to call Url in url.js from runner.js.

runner.js

define(['url'], function (url) {
  "use strict";

  function someParsing() {
    var urlText, url1;
    urlText = "http://www.stackoverflow.com";
    url1 = new Url(urlText);
    return url1;
  }
  return {
    someParsing: someParsing
  }
});

url.js

define(function () {
  "use strict";

  function Url(urlText) {
    return urlText;
  }
  return {
    urlText: urlText
  }
});

the error I get

TypeError: 'undefined' is not a constructor (evaluating 'new Url(urlText)')

What is the correct way to set this up so I can use the Url constructor in runner.js?

3
  • 1
    Where is define coming from? RequireJS? Commented Aug 14, 2015 at 22:41
  • ^ are you using a library or framework that allows you to require other modules? Commented Aug 14, 2015 at 22:49
  • Yes, this is RequireJS. Commented Aug 15, 2015 at 3:04

1 Answer 1

2

Looks like you're using require.js, yes?

short answer:

in url.js:

define(function () {
    "use strict";
    function Url(urlText) {
        return urlText;
    }
    return Url;
}

in runner.js:

define(['url'], function (Url) {

long answer:

Notice that you pass in an anonymous function to define. This is code that defines your module when require.js decides to run it. Any var or function declaration inside that function is in the local scope.

The way you make objects available to other modules is by returning them (from your module-definition function). Whatever you return is what require.js supplies to other modules that ask for the module you just defined.

So, if you return the Url constructor in url.js, when you ask for the 'url' module in runner.js, require.js will pass the Url constructor to your 'runner' module definition function.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the thorough explanation. very informative. exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.