使用 $.fn 时访问范围为 "this"。和 $('#test').demo();

Access scope with "this" when using $.fn. and $('#test').demo();

我希望这不是一个非常愚蠢的问题,但我对 jQuery 在使用其原型函数时如何处理 this 属性 感到有点困惑。

将参数传递给函数时,例如 $.fn.demothis 的值将包含参数中传递的 DOM 对象,在本例中为匹配选择器的对象#test:

$('#test').demo({test: 'test1'});

使用带参数的 jQuery 原型函数时是否可以访问函数作用域? 我的目标是动态定义范围变量,我通常会使用 this['demo'] = 'aaa'

如果不在 this 中,它们存储在哪里?

Code online

$.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" 范围内添加变量那么当你使用它时你应该使用 "this" 就像@MinusFour已经说过的或者你想在函数范围内添加变量然后使用eval,您可以在js代码下面看到差异;

$.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];
        eval("var " + key+"='"+classes[key]+"'");
    }
    console.log(this);

    console.log(helloText);

    //fails to print the value of "pepe", it doens't exist in the scope
    console.log(this.pepe);
    console.log(pepe);
};

$('#test').demo({test: 'test1'});

浏览器 Javascript 的全局对象是 window 对象。所以你可以像这样修改你的部分代码,它会起作用:

for (var key in classes) {
    window[key] = classes[key];
}

然而,将东西写入 window 对象通常不是一个好主意,因为一切都可以从那里写入和读取。防止这种情况的方法是:

(function() {
  var myEncapsulatedValues = {};

  var myJQueryFunction = function() {
    var classes = {
      wrapper: 'Yay it works!!',
      pepe: 'demo'
    };
    
    for (var prop in classes) {
      myEncapsulatedValues[prop] = classes[prop];
    }
  };

  myJQueryFunction();

  console.log(myEncapsulatedValues['wrapper']);

})();

// But I cant access encapsulated values here
console.log(typeof myEncapsulatedValues);

这是Javascript中模拟封装的一种基本方式,称为IIFE(Immediately Invoked Function Expression)。

如果您是 Javascript 的新手,有很多东西需要学习。范围、上下文、闭包、提升、模块。即使知道他们的名字也会让你更有能力解决你将要面对的困难。你可以得到基本的想法here.