[英]Unable to access method in object literal
在对象字面量中,我们应该能够使用this.name
访问方法,但是在下面的例子中,我使用this.init()
来触发方法,但是给了我未定义的函数。 但是,如果我引用allTabAnimation.init()
可以正常工作,那为什么呢?
var allTabAnimation = {
desktopClick: function (){
$('.allForms .investorOptions .investorOptions-wrapper .select-options input+label').click(function (e){
$this = $(this),
$thisHookNumber = $(this).data("hook"),
$allTab = $(".tab-content"),
$selectedTab = $(".tab-content[data-hook="+$thisHookNumber+"]"),
this.init(); // doesn't work
// allTabAnimation.init(); // this work
});
},
init: function (){
this.condition($selectedTab, $allTab);
},
存储this
变量(或使用.bind
,或$.proxy
),因为在你的情况下, this
是指元素不是父对象,像这样
var allTabAnimation = {
desktopClick: function() {
var self = this;
$('.allForms .investorOptions .investorOptions-wrapper .select-options input+label').click(function(e) {
$this = $(this),
$thisHookNumber = $(this).data("hook"),
$allTab = $(".tab-content"),
$selectedTab = $(".tab-content[data-hook=" + $thisHookNumber + "]")
self.init();
});
},
init: function() {
this.condition($selectedTab, $allTab);
}
}
范围(此)在回调中发生变化,这就是为什么您需要将其声明为变量的原因。 遵循约定,您应该使用
var that = this;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.