gpt4 book ai didi

javascript - jQuery Javascript 将父对象传递为 this

转载 作者:行者123 更新时间:2023-12-02 19:56:27 25 4
gpt4 key购买 nike

我想将当前调用的对象及其当前设置的参数传递给闭包函数。我不确定一般如何做到这一点,但我认为 jQuery 又增加了一层困惑,因为 this 引用了一个元素。

示例:

jQuery 插件

(function( $ ){
$.fn.addContentType = function(obj) {
var name = "this is just an example";
obj.func.call(this); //<--I want to pass this object, not the jQuery selector
};
})( jQuery );

调用插件

jQuery("#someelement").addContentType({
func:function(){
console.log(this.name); //<--Expect "this is just an example"
}
});

有什么想法可以做到这一点吗?

这只是一个例子,没有做任何事情,我只是想展示我想要的东西。如果我缺少详细信息,请告诉我。

最佳答案

要访问 name 作为 jQuery 对象的属性,您需要添加它而不是使用变量。

this.name = "this is just an example";
obj.func.call(this);
<小时/>

或者使用变量将值传递给函数:

var name = "this is just an example";
obj.func.call(this, name);

并在另一端接收:

func:function( name ){
console.log( name ); //<--Expect "this is just an example"
}
<小时/>

或者要使您的 obj 成为 this 值,请执行以下操作:

obj.func.call(obj, name);

...但您仍然需要传递参数,除非您将值作为属性分配给 obj

关于javascript - jQuery Javascript 将父对象传递为 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8554084/

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