te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>html - How to create and implement a custom JavaScript library - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to create and implement a custom JavaScript library - Stack Overflow

programmeradmin3浏览0评论

I am new to javaScript and am unsure how to go about creating a new js library and referencing this in another js file.

If I have a standalone file Utilities.js

var Utilities= 
{
   show: function(input)
   {
      alert(input);
   }
};

Am I missing something as to how a library should be defined standalone?

My second question is how to use that is sub-sequent js files. What I did so far is:

<script type="text/javascript" src="resources/Utilities.js"></script>

In my index.html. Is this enough to reference it as:

Utilities.show("Hello");

In any other java script file?

I tested it in this fashion and got and error "Utilities is not defined"

NOTE: This is just an example and not my full and practical purpose.

I am new to javaScript and am unsure how to go about creating a new js library and referencing this in another js file.

If I have a standalone file Utilities.js

var Utilities= 
{
   show: function(input)
   {
      alert(input);
   }
};

Am I missing something as to how a library should be defined standalone?

My second question is how to use that is sub-sequent js files. What I did so far is:

<script type="text/javascript" src="resources/Utilities.js"></script>

In my index.html. Is this enough to reference it as:

Utilities.show("Hello");

In any other java script file?

I tested it in this fashion and got and error "Utilities is not defined"

NOTE: This is just an example and not my full and practical purpose.

Share Improve this question edited Jun 23, 2015 at 21:26 cain4355 asked Jun 23, 2015 at 21:13 cain4355cain4355 1,1542 gold badges12 silver badges22 bronze badges 10
  • 1 Might I suggest following a pattern where users of your library can bundle things with Browserify? browserify – Brad Commented Jun 23, 2015 at 21:14
  • 1 That does not answer either of my questions. – cain4355 Commented Jun 23, 2015 at 21:16
  • 2 So far that looks fine to me. I don't think this question is adequately scoped here though. – Travis J Commented Jun 23, 2015 at 21:17
  • So if that first part of code is the only thing in my Utilities.js file then it can be properly referenced? Also is Utilities.show("X"); how I would use it? – cain4355 Commented Jun 23, 2015 at 21:19
  • @MatthewSegreti Actually, it does. But I posted it as a ment in any case. – Brad Commented Jun 23, 2015 at 21:21
 |  Show 5 more ments

5 Answers 5

Reset to default 6

Yes, including that Javascript file with that global variable declared is enough to call your methods this way Utilities.show("Hello"); from another Javascript file loaded after Utilities.js or inside a <script></script> section of your html.

But you can actually improve it a little, following the module pattern and exposing only the functions you really need to the global scope (you'll likely write some functions that the users of your library should not call directly, this allows you to do it in a clean way):

var Utilities=Utilities||(function () {

   //Accessible only here
   var privateArray=[];

   //Cannot be called from outside this function
   var privateFunction=function(){
   }

   //Return only what must be publicly accessible, in this
   //case only the show() method
   return {
      show: function(input){
         privateFunction();
         alert(input);
      }
   }
})();

That (function () { /* Code */})();, defining a new scope for your code will also avoid name clashes with other global javascript object/functions.

  1. It is OK to use object literals, but you can define libraries using other patterns (module, revealing module, constructors, etc).

I remend these links to understand primitives, scopes, closures, object literals, etc.

http://bonsaiden.github.io/JavaScript-Garden/

http://jsbooks.revolunet./

  1. To call the method inside index.html you need to add a tag.

    <script> Utilities.show("Hello"); </script>

But this approach it's not remended. Instead of it, you can create a new JS file to run your library code.

<script type="text/javascript" src="resources/Utilities.js"></script> <script type="text/javascript" src="resources/main.js"></script>

In main.js

Utilities.show("Hello");

Hope it helps.

Given the fact that you gave, within yout question, zero context of what you're trying to achieve, the best answer to your original question is that it depends.

If you just need a bunch of files and you're done (like in your example, Utilities.js and a few more) then you're ok with the way you're heading to.

But of course, you'll allways want to scale your front end and thus you should adhere to some architectural pattern. So, if you're building a client side (browser-side) application, then you should really implement your libraries using the module pattern, and begin your project from a good project example / scaffold.

On the other hand, if you're rendering the html on server (e.g. you're using PHP to render the final html file that will be sent to browser) and you just need some thin functionality in the browser, the way you begun can be okay if you're careful. Also, you can still implement the module pattern here too, although I strongly suggest that you should make use of namespacing to have a clear separation of concerns.

Creating a custom JavaScript library is a great deal. For that, you must create a separate Javascript file that would contain all your library code e.g Library.js . You can use this model as an example:

    // Library.js code

    const Utilities= 
    {
      show: function(input)
        {
          alert(input);
        }
    };

  export default Utilities;



// your other JS file where you want to use your library

import Utilities from 'path/to/Library.js';

Utilities.show("hello world!")
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>Title of the document</title>
    </head>
    <body>

    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>


    <script src="Library.js"></script>
    </body>
    </html>

This export will export your whole code in Utilities as default so you could easily use all the methods and properties inside Utilities constant .

In browser based javascript you can't just call functions from different files yet. In Es6 there are ways. But not yet. Which mean just because you have some variable or function etc then you cant reference it automatically in another file.

Unless both files are loaded into one html and are loaded in order.

Alternatively you could run task runner like grunt and 'merge' them upon each build.

Javascript doesnt have special concept of library, in es6 it's a little different, everything is an object.

What you are doing is just creating an object. and yes it will work.

发布评论

评论列表(0)

  1. 暂无评论