2017-04-20 04:56
浏览 21


I want to set my function in global js. So it can called from anywhere

I have function this :

$(function () {
    function formatCurrency(input) {
        return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

I put the function on the


And I add this : <script src="{{URL::asset('/resources/assets/js/main.js')}}"></script> on the


When executed, on the console exist error like this :

GET http://mysystem.dev/resources/assets/js/main.js 404 (Not Found)

How can I solve it?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongpi9480
    dongpi9480 2017-04-20 05:19

    The issue seems to be you're using asset() wrong.

    asset refers to a file in /public.

    You should compile/minimize your JS for production and put it somewhere in /public, i.e. /public/js/my.js

    点赞 评论
  • duan4523
    duan4523 2017-04-20 04:58

    You can define global function like this

    window.formatCurrency = function(input){
                return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

    and you are define function in ready function($(function)) then you must call this in ready function also. So better define it outside of ready function or in self invoking function.

    点赞 评论
  • douciping4283
    douciping4283 2017-04-20 04:58

    You should define you function as a method of the window object.

    window.formatCurrency = function(input) {
        return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

    Another more clean way it would be to define your function as a method of an object called Utils, like below:

    var Utils = (function(){
        function formatCurrency(input){
            return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
        return {
            formatCurrency: formatCurrency

    Doing so, you will not pollute the global namespace. You will have only one variable defined in the global namespace called Util, which would contain an obejct with useful functions that can be used by other parts of your application. As it is you can't see the benefits of the latter approach. However you can consider how it would be if you wanted to use 3 more functions, that by their own use 2 other functions as helpers. If that was the case your return statement would also contained the 3 more functions, whereas the 2 functions I mentioned before wouldn't be epxosed at all !

    点赞 评论