【发布时间】:2017-10-03 15:25:10
【问题描述】:
我希望这不是一个非常愚蠢的问题,但我对 jQuery 在使用其原型函数时如何处理 this 属性感到有些困惑。
将参数传递给$.fn.demo等函数时,this的值将包含参数中传递的DOM对象,在这种情况下与选择器#test匹配的对象:
$('#test').demo({test: 'test1'});
在使用带参数的 jQuery 原型函数时是否可以访问函数范围?
我的目标是动态定义范围变量,我通常会使用this['demo'] = 'aaa'
如果不在this 中,它们会存储在哪里?
$.fn.demo = function(options){
var helloText = "hello";
// keeping central set of classnames and selectors
var classes = {
wrapper: 'wrapper',
pepe: 'demo'
};
//this has the #test DOM object value, not the function scope
console.log(this);
//trying to assign the object keys to the global scope
for (var key in classes) {
this[key] = classes[key];
}
console.log(helloText);
//fails to print the value of "pepe", it doens't exist in the scope
console.log(pepe);
};
$('#test').demo({test: 'test1'});
【问题讨论】:
-
this不是 DOM 对象,而是 jquery 对象实例。 -
@MinusFour nvm 我错了
-
如果你使用
this.pepe而不是pepe它应该可以工作 -
@MinusFour 我想避免使用对象属性。他们最终使代码更长,并且没有使用常见的缩小器进行缩小。
-
你还必须避免
this[key]。您可以动态创建变量的唯一方法是通过 eval,而且更糟。
标签: javascript jquery jquery-plugins