如何在不同的脚本和div元素中调用子函数

时间:2015-11-06 17:52:35

标签: javascript

我有一些像这样的代码:

function A() {
  this.Test = (function () {
    // some code here
    function B() {
      // some code here
    }
    function c() {
      // some code here
    }
    return { B: B };
  })();
}

我想在另一个脚本中调用B函数。我添加了这段代码:

var testing = new A();

到新脚本并调用它:

testing.Test.B();

然而它并不起作用。 我还需要在B元素中调用函数div

<div onmousedown="testing.Test.B();">
...
</div>

但我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

尝试test.Test();而不是testing.Test.B();

答案 1 :(得分:0)

你在做什么似乎对我有用;见this fiddle

&#13;
&#13;
var A = function () {
	alert('A!');
	this.Test = (function () {
		var B = function () {
			alert('B!');
		};
		return {
			B: B
		}
	})();
};

window.testing = new A(); // var testing =... will work as well if the whole code isn't wrapped in another function.
testing.Test.B();
&#13;
&#13;
&#13;