如何从JavaScript中的对象中的函数调用另一个函数。
例如,我试图这样做:
var mydiv1 = document.querySelector('.div1');
var mydiv2 = document.querySelector('.div2');
var myVariable1;
var myVariable2;
var myObject = (function() {
return {
function1 : function (myVariable1) {
myVariable2 = "this was called from a function and inserted by function2";
mydiv1.innerHTML = myVariable1;
function2(myVariable2);
},
function2 : function (myVariable2) {
mydiv2.innerHTML = myVariable2;
}
};
}());
mydiv1.addEventListener('click', function() {
myVariable1 = "this was called from a function and inserted by function1";
myVariable2 = "this was called from a function and inserted by function2";
myObject.function1(myVariable1);
});
这是一个小提琴http://jsfiddle.net/kvtxd/6/
"功能1"运行为例外,但我得到一个错误,函数2未定义。这样做的正确方法是什么?
我使用对象的原因是,如果需要,我可以单独调用每个内部函数。即只调用function2但不调用function1。
请参阅,如果我使用:
function WholeFunction() {
function function1() {
//
}
function function2() {
//
}
}
然后function1和function2超出了范围,我只能调用整个事情。
答案 0 :(得分:2)
使用"此"函数内部的关键字:
function1 : function (myVariable1) {
myVariable2 = "this was called from a function and inserted by function2";
mydiv1.innerHTML = myVariable1;
this.function2(myVariable2); // use "this" here!!!!
},
这里是Fiddle
答案 1 :(得分:0)
您可以使用this
访问同一对象的属性。我把它添加到你的小提琴中: