gpt4 book ai didi

javascript - 对此感到困惑 - 出现错误 "this.myfuntion() is not a function"

转载 作者:行者123 更新时间:2023-11-28 16:14:30 25 4
gpt4 key购买 nike

背景:我正在尝试编辑 zen cart 水平弹出菜单,以使弹出窗口在菜单内内联打开。我遇到的问题是我很难理解它附带的 javascript/jquery。

在不发布整个内容的情况下,代码结构如下:

(declare some vars)

//some functions like this:
function funcname(obj) {
//do something
}

//then one big master function like this:
function bigfunc(arg1, arg2, arg3, arg4, arg5) {

//declare some vars based on this
this.varname1=varname1;
this.varname2=varname2;

//declare some functions inside the big function
this.innerfunc1= function() {
//do stuff
}

this.innerfunc2= function() {
//do stuff
}

}//end of big function

//then goes on to declare init function

function initfunc(){
//this creates new bigfunc(arg1 arg2 arg3...) for each main menu item
}

//finally calls init function with
window.onload = initfunc();

现在说说我的困惑 -

1)首先澄清一下,基于 bigfunc() 中漂浮的所有 this 以及使用 new bigfunc() 调用它正在创建一个对象的事实,我的想法是否正确?

2)我当前的问题是 bigfunc() 内的函数之一,如下所示:

this.slideChildMenu = function() {
var divref = this.children[0].div;
var ulref = this.children[0].ul;
var maxwidth = this.children[0].width;
var nextWidth;
if (this.isMouseOnMe || this.isMouseOnChild()) {
nextWidth = divref.offsetWidth + slideSpeed_out;
if (nextWidth >= maxwidth) {
this.finishOpeningChild(divref, ulref, maxwidth);
} else {
ulref.style.left = nextWidth - maxwidth + "px";
divref.style.width = nextWidth + "px";
setTimeout("slideChildMenu('" + this.getId() + "')", slideTimeout_out);
}
}

现在我的计划是改变它以使用 jquery show 打开元素,所以我尝试了这个:

this.slideChildMenu = function() {
var divref = this.children[0].div;
var ulref = this.children[0].ul;
if (this.isMouseOnMe || this.isMouseOnChild()) {
$(divref).show(function(){
this.finishOpeningChild(divref, ulref);
});
}
}

但是我得到了这个-> TypeError: this.finishOpeningChild 不是一个函数

现在,这个 js 中还发生了很多其他事情,所以我不会梦想让这里的人为我做我的工作,但我希望如果有人可以向我解释为什么这个函数不是一个我也许可以解决剩下的问题。

注意:我认为这与“this”的范围有关,但在两个版本的代码中,this 的值似乎完全相同。

我知道这很长,但非常感谢您的帮助。

最佳答案

函数中 this 的值称为函数运行的“上下文”。一般来说,每当您将回调函数作为参数传递时(就像您使用 $(divref).show(function() {...}) 所做的那样),该函数可以以任何方式运行回调它想要的上下文。在本例中,jQuery show 函数选择在动画元素的上下文中运行其回调。

但是,您希望在匿名回调函数定义时(而不是运行时)访问 this 的值。这里的解决方案是将 this 的外部值存储在一个变量(传统上称为 self)中,该变量包含在新定义的函数的范围内:

this.slideChildMenu = function() {
//...
var self = this;
$(divref).show(function(){
self.finishOpeningChild(divref, ulref);
});
}

关于javascript - 对此感到困惑 - 出现错误 "this.myfuntion() is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com