Clinton Lam
Clinton Lam

Reputation: 727

Why `this` property cannot access within function

The Problem

I am working on a jQuery plugin. When called with $.fn.bar(), the alert() within foo() is not outputting the expected result. Where did I make the mistake?

(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));

Solution

You need to pass the context this within bar() to foo() with foo.call(this).

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

Upvotes: 2

Views: 40

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

You should .call the foo function with whatever this is inside bar, so that bar's calling context gets transferred to foo:

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>

Upvotes: 2

Related Questions