jquery/ javascript中self的用途是什么?

What is use of self in jquery/ javascript?

本文关键字:是什么 self javascript jquery      更新时间:2023-09-26

在javascript中,他们使用的是:

  • var self=this;
  • var jquery_element= $(html_element);
  • self.jquery_element=jquery_elemnet

为什么我们在javascript中使用这些呢?这段代码来自OpenStack horizon

var self=this;是有用的,当你有嵌套函数和this可以变得模棱两可(如果你不知道this是一个javascript关键字)。self仍然可以用来改变this,现在从内部函数指向this

var jquery_element= $(html_element);只是提供了一种简单的方法来引用jQuery元素,而不必经常重新创建它(也提供了性能优势,例如这里解释的)。

self.jquery_element = jquery_element似乎是特定于该代码,我不太确定它的作用

这是为了在其他范围内可见,在一个范围内使用this编辑。

 var parentFunction = function(){
       this.msg = "hello world";
       var parentScopeSelf = this;
       var innerFunction = function(){
            var innerFunctionScopeSelf = this;
            console.log(this.msg);// undefined (because this now is   innerFunction scope, and does not have property msg)
            console.log(innerFunctionScopeSelf.msg);// undefined (because innerFunctionScopeSelf is "this" from  innerFunction scope, and does not have property msg)
            console.log(parentScopeSelf.msg);// hello world (because parentScopeSelf is "this" from parentFunction scope)
       }
    }

回答你的直接问题,this是一个javascript 关键字,它的值会根据它的位置而改变。通过将其值写入像self这样的常规变量,即使this本身发生了变化,也可以保留self在范围内的值。

当您有嵌套函数时,将this分配给另一个变量是有用的。例如:

jQuery(function($) {
    $('#myInput').on('keyup', function() {
        var $this = $(this); // assign the jQuery's element to $this
        $('div.errors').each(function() {
            console.log($(this)); // outputs jQuery's object div.errors
            console.log($this); // the input is still available in the nested function
        });
    });
});

作为建议,如果变量存储jQuery元素,请在其前面加上$。因此,它应该是

var $jquery_element = $(html_element);

var jquery_element= $(html_element);

是使HTML元素成为一个jquery对象,可以使用jquery的所有方法。

html_element.fadeOut(); <——将不工作

$(html_element).fadeOut(); <——将工作