gpt4 book ai didi

javascript - 为什么我不能调用对象内部的值?

转载 作者:行者123 更新时间:2023-11-28 17:13:37 25 4
gpt4 key购买 nike

自从我开始制作插件几天后,我想知道这两个代码之间有什么区别以及为什么第二个代码不起作用。

第一个看起来像这样:

<div class="searching">
<ul>
<li></li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

(function($) {
$.fn.slideInit = function() {
const myGallery = $(this),
myList = myGallery.find('li');

<!-- Log Section -->
console.log(myList);
<!----------------->
};
} (jQuery));
$('.searching').slideInit();

这段代码工作正常,符合我的预期。变量myGallery可以在代码块内部定义。

第二个不起作用的看起来像这样:

(function($) {
$.fn.slideInit = function() {
const defaults = {
myGallery: $(this),
myList: myGallery.find('li')
};

<!-- Log Section -->
console.log(defaults.myList);
<!----------------->
};
} (jQuery));
$('.searching').slideInit();

我在这段代码中所做的只是在一个名为 defaults 的对象中添加了变量,但是当我运行这段代码时,会弹出一个错误:

index.html:59 Uncaught ReferenceError: myGallery is not defined

我认为这两个代码之间有一些区别,但我自己找不到或弄清楚。

你们能告诉我为什么无法定义变量 default 作用域的 myGallery 吗?

最佳答案

您必须在文字之外定义您的 var 或使用 this 引用它

const defaults = {
myGallery: "DONALD DUCK",
myList: function() { console.log(this.myGallery) }
};

defaults.myList();

关于javascript - 为什么我不能调用对象内部的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53943967/

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