Javascript 如何从内部嵌套函数调用父函数?
我有一个简单的jQueryJavascript 如何从内部嵌套函数调用父函数?,javascript,Javascript,我有一个简单的jQueryready事件,它通过调用setupView对象中的a函数来初始化视图 我的问题是,从init函数调用函数setSomethingImportant的合适方法是什么,如下所示 由于调用是从不同于init函数的执行上下文中进行的,this.setSomethingImportant()不起作用。但是,如果我使用setupView.setSomethingImportant(),它就可以工作。我遇到的问题是,如果var名称(setupView)更改,我也必须更改代码体
ready
事件,它通过调用setupView
对象中的a函数来初始化视图
我的问题是,从init
函数调用函数setSomethingImportant
的合适方法是什么,如下所示
由于调用是从不同于init
函数的执行上下文中进行的,this.setSomethingImportant()
不起作用。但是,如果我使用setupView.setSomethingImportant()
,它就可以工作。我遇到的问题是,如果var名称(setupView
)更改,我也必须更改代码体
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant();
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);
只需单独声明函数,然后像这样调用:
function setSomethingImportant(context) {
context.currentState="TC";
console.log("Something has changed :" + context.currentState );
};
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change( function () {
console.log("Changed =" + $(this).val());
setSomethingImportant(this);
// Question ? how to call a method in the setupView object
});
},
setSomethingImportant : function () {
setSomethingImportant(this);
}
}
}(jQuery);
将此存储到变量中:
var setupView = {
currentState: "CT",
init: function() {
// Keep a reference to 'this'
var self = this;
$("#externalProtocol").change(function() {
console.log("Changed =" + $(this).val());
// Use the old 'this'
self.setSomethingImportant();
});
},
setSomethingImportant: function() {
this.currentState = "TC";
console.log("Something has changed :" + this.currentState);
}
};
请注意,我更改了原始解决方案。我现在使用将数据传递给事件处理程序
您仍然在
change
处理程序中传递错误的上下文。谢谢@Florent。老实说,我一直在使用你建议的方法。但我不确定将“this”存储在变量中是否是最佳实践。有时您没有选择。你越少使用这个技巧,你的代码就会越干净。
(function() {
$(document).ready(function() {
setupView.init();
});
var setupView = {
currentState : "CT",
init : function () {
$("#externalProtocol").change({ _this: this }, function (event) {
console.log("Changed =" + $(this).val());
event.data._this.setSomethingImportant();
});
},
setSomethingImportant : function () {
this.currentState="TC";
console.log("Something has changed :" + this.currentState );
}
}
}(jQuery);