简体   繁体   中英

How to call a function in another Javascript file from a constructor?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM