javascript 在不同的 .js 文件中使用两个同名方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3492636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:19:49  来源:igfitidea点击:

Use two methods of the same name in different .js files

javascript

提问by Pankaj

I have two methods with the same name, for different purposes in 2 different .js files. How can I use those methods on same page?

我在 2 个不同的 .js 文件中有两个同名的方法,用于不同的目的。如何在同一页面上使用这些方法?

In Count.js:

在 Count.js 中:

function add()
{
// some manipulation doing here
}

In PriceImplement.js

在 PriceImplement.js 中

Function add()
{
// some manipulation doing here
}

回答by PatrikAkerstrand

You should get into the habit of namespacing your JavaScript-files:

你应该养成命名你的 JavaScript 文件的习惯:

//Count.js:

//计数.js:

var Count = {
  add: function add() {
  },
  [additional methods in the Count object]
};

// PriceImpl.js

// PriceImpl.js

var Price = {
  add: function add () {
  },
  [additional methods for the Price implementation]
};

Then call methods like Namespace.method, i.e. Price.add()

然后调用方法一样Namespace.method,即Price.add()

回答by Marcel Korpel

If they're both defined using function declarations, like

如果它们都是使用函数声明定义的,比如

function iHaveTheSameNameAsAnotherFunction(params) {
    …
}

then you can't. The second declaration will simply overwrite the first one.

那么你不能。第二个声明将简单地覆盖第一个声明。