代码之家  ›  专栏  ›  技术社区  ›  Clinton Lam

为什么“this”属性不能在函数内访问

  •  2
  • Clinton Lam  · 技术社区  · 6 年前

    问题

    我正在开发一个jquery插件。当与呼叫时 $.fn.bar() ,foo()中的alert()未输出预期结果。我在哪里犯的错误?

    (function($){
    
      var input;
    
      var foo = function(){
        alert(this.input); //<-- Not getting the desire input value
      }
    
      $.fn.bar = function(){
    
        this.input = "Test";
    
        alert(this.input); //<-- Output "Test" as expected
        foo(); //<-- Call foo(), expect to alert "Test" as well, but not
    
      };
    
    
    }(jQuery));
    

    解决方案

    你需要传递上下文 this 在内部 bar() foo() 具有 foo.call(this) .

    https://jsfiddle.net/clintonlam/de1vz59w/8/

    1 回复  |  直到 6 年前
        1
  •  2
  •   CertainPerformance    6 年前

    你应该 .call 这个 foo 任何功能 this 在里面 bar ,这样 酒吧 的调用上下文被传输到 :

    var foo = function() {
      console.log('foo', this.input);
    };
    $.fn.bar = function() {
      this.input = "Test";
      console.log('bar', this.input);
      foo.call(this);
    };
    
    $().bar();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>