gpt4 book ai didi

javascript - 关于 jquery 在一个类中的作用域

转载 作者:行者123 更新时间:2023-11-30 09:05:49 25 4
gpt4 key购买 nike

我希望能够通过 ajax 调用 info['id']...

var setEditor = function()
{
this.info = {
'id' : 1 // <--------------- i want this
};

var cardEditor = function()
{
var status = {
'touched' : false,
'id' : 0
};
card.children('input').bind('focusout', function() {
alert(this.info['id']); // <----------------- through this
$.ajax({
type : 'POST',
url : '../addcard',
data : 'name=John&location=Boston',
dataType : 'json',
success: function(msg){
$('#rec').html(msg);
}
});
});

};
};

set = new setEditor();

最佳答案

问题是 this 是一个关键字,它会在不同的时间指代不同的事物。诀窍是创建一个新变量 that,方法是在 this 引用时将 this 赋值给它你想要什么。然后它可以通过词法作用域被嵌套函数访问。我通常会在构造函数的顶部执行一次。

var setEditor = function()
{
var that = this; // that is not a keyword and will always refer this as it is
// interpreted at the line of assignment (until that itself is
// redefined of course). this will mean something
// else when run in an event handler.

this.info = {
'id' : 1 // <--------------- i want this
};

var cardEditor = function()
{
var status = {
'touched' : false,
'id' : 0
};
card.children('input').bind('focusout', function() {
alert(that.info['id']); // now refers to the object and not the input
// element.
$.ajax({
type : 'POST',
url : '../addcard',
data : 'name=John&location=Boston',
dataType : 'json',
success: function(msg){
$('#rec').html(msg);
}
});
});

};
};

set = new setEditor();

关于javascript - 关于 jquery 在一个类中的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111973/

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