gpt4 book ai didi

javascript - 在 jQuery 中引用变量中的选项

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:50:29 26 4
gpt4 key购买 nike

只是对 jQuery/Javascript 感兴趣并引用变量中的选项。

所以,我写了一个小插件,当我调用“populate”时,它会填充一些文本。非常基本。这是我正在尝试做的事情:

var foo = {
msg1: "Hey",
msg2: this.msg1 + "how",
msg3: this.msg2 + "are",
msg4: this.msg3 + "you",
msg5: this.msg4 + "doing",
msg6: this.msg5 + "today"
}

$("#bar").populate({text: foo.msg6});

因此,当调用 .populate 插件时,#bar 将添加“Hey how are you doing today”。

populate 插件很难解释,但请相信我,它工作得很好,不是问题所在。我只是好奇这种变量和选项的组织方式是否可行,因为对我来说它看起来更清晰、更“语义化”、更有条理,而不仅仅是一堆引用其他变量的变量。 ..

最佳答案

this 仅在执行上下文 中有意义。当您定义一个函数时,会为该函数创建一个作用域链,该作用域链将在该函数进入当前执行上下文时使用。发生这种情况时,this 将被定义(在运行时)。参见 this了解更多详情。

在您的示例中,您没有定义任何新的作用域链,因为您没有在您的对象上创建任何方法。因此,当您引用 this 时,无论何时创建 foo 对象,您都指的是 this。很可能,您在全局空间中工作,所以 this 将是 window(如果您在浏览器中),但它可能是另一个具有函数的对象你当前正在执行的。例如:

    var myScopeObj = {
myMethod: function() {
var foo = {
msg1: "Hey",
msg2: this.msg1 + "how",
msg3: this.msg2 + "are",
msg4: this.msg3 + "you",
msg5: this.msg4 + "doing",
msg6: this.msg5 + "today"
};
var foo2 = foo.msg6;
}
};

上面的例子有两种可能性:

    myScopeObj.myMethod();  // 'this' refers to myScopeObj

    var method = myScopeObj.myMethod;
method(); // 'this' refers to window

    myScopeObj.myMethod.call(window);  // 'this' refers to window

您可以做的是为您的对象使用构造函数,并使用 this 映射属性。

    function Foo() {
this.msg1 = "Hey";
this.msg2 = this.msg1 + "how";
this.msg3 = this.msg2 + "are";
this.msg4 = this.msg3 + "you";
this.msg5 = this.msg4 + "doing";
this.msg6 = this.msg5 + "today";
};
var foo = new Foo();
$("#bar").populate({text: foo.msg6});

关于javascript - 在 jQuery 中引用变量中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112676/

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