如何在javascript / jquery中限制函数的范围

时间:2015-11-24 06:16:44

标签: javascript jquery scope

我在页面上链接了多个 var legendname = ["Yes","No"]; var legend = svg.selectAll(".legend") .data(legendname) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(" + (w + 150) + "," + (m.t - 30) + ")"; }); legend.append("path") .attr("d", d3.svg.symbol().type("triangle-up").size(128)) *** .attr("y", function(d,i) {return 50+i*40;}) .style('fill', function(d) {return color(d);}); legend.append("text") .attr("y", function(d,i) {return 50+i*20;}) .attr("x", 30) .text(function(d) { return d; }) 文件,这些文件具有相同名称的功能,如跟随模型

first.js

.js

second.js

function DisplayContent(data,$target) // data is string
{
     $target.html('<span>'+ data +'</span>')
}

上述两个文件都被引用到该页面。

如何在不重命名功能的情况下修复上述问题。

如果接近错误,请更正。

由于

5 个答案:

答案 0 :(得分:2)

您可以在JavaScript文件中使用命名空间:

  

first.js:

var first= {
  DisplayContent: function DisplayContent(data,$target) 
  {
     $target.html('<span>'+ data +'</span>')
  },
     [additional methods in the first object]
};
  

second.js

var second= {
  displayContent: function DisplayContent(data,$target) 
  {
      $target.html('<div>'+ data +'</div>')
  },
  [additional methods for the second implementation]
};

然后调用Namespace.method之类的方法,即first.DisplayContent()

答案 1 :(得分:1)

我猜是

function DisplayContent(data,$target,htmltag) // data is string
{
     $target.html('<' + htmltag + '>' + data + '</' + htmltag + '>')
}

答案 2 :(得分:1)

如果您只在该文件中调用这些函数 ,那么您可以限制范围如下:

<强> First.js

(
  function(){
    function DisplayContent(data,$target) // data is string
    {
         //$target.html('<span>'+ data +'</span>')
         alert("first file");
    }

    DisplayContent('test','test');

    //here you can place other code
}());

<强> Second.js

(
  function(){
    function DisplayContent(data,$target) // data is string
    {
         //$target.html('<div>'+ data +'</div>')
         alert("Second file");
    }

    DisplayContent('test','test');

    //here you can place other code
  }()
);

See a demo

答案 3 :(得分:0)

多种方式。

  1. 你可以在你的second.js中执行此操作,如果你不想要他们的话。这将允许您在页面中独立使用second.js,此功能将触发。

     if(typeof DisplayContent !=='function'){
        function  DisplayContent(){
    
      }
     }
    
  2. 你可以像曼瓦尔那样正确地关闭。

  3. 但是,拥有两个具有相同名称的功能并没有多大意义。你应该避免这种情况。

答案 4 :(得分:-1)

如果将两个JS文件添加到单个页面,则两个文件将在单个javascript上下文中运行,并且将替换这些函数,使得结果不可接受。因此,制作你的要求是不可能的。