简体   繁体   English

如何从构造函数调用另一个Javascript文件中的函数?

[英]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. 我正在处理url处理类,并希望通过构造函数访问它。 For example, calling new Url(" http://www.stackoverflow.com?param=value ") would return different components of the url. 例如,调用new Url(“ http://www.stackoverflow.com?param=value ”)将返回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调用url.js中的Url。

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 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)') TypeError:“未定义”不是构造函数(正在评估“ new Url(urlText)”)

What is the correct way to set this up so I can use the Url constructor in runner.js? 什么是正确的设置方式,以便可以在Runner.js中使用Url构造函数?

Looks like you're using require.js, yes? 看起来您正在使用require.js,是吗?

short answer: 简短答案:

in url.js: 在url.js中:

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

in runner.js: 在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. 这是在require.js决定运行模块时定义模块的代码。 Any var or function declaration inside that function is in the local scope. 该函数内部的任何var或函数声明都在本地范围内。

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. 无论您返回什么,require.js都会为其他模块提供所需的内容,这些模块要求您刚刚定义的模块。

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. 因此,如果您在url.js中返回Url构造函数,则当您在Runner.js中要求“ url”模块时,require.js会将Url构造函数传递给您的“ runner”模块定义函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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