【问题标题】:Why `this` property cannot access within function为什么`this`属性不能在函数内访问
【发布时间】:2019-02-19 07:16:41
【问题描述】:

问题

我正在开发一个 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));

解决方案

您需要将bar() 中的上下文this 传递给foo()foo.call(this)

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

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

    你应该.callfoo函数与thisbar内,以便bar的调用上下文被转移到foo

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

    【讨论】:

    • 如果我也想将值传递给 foo,我应该怎么做? foo.call(this, values)?
    • 是的,valuesfoo 的第一个参数
    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    相关资源
    最近更新 更多