-3
$("btn").click(function(){
     function(){
      console.log(this);
   }
})

Hi All, where "this" is refering in this piece of code?A interviewer asked me,i got confused.Please suggest.Thanks

Leo
  • 163
  • 13
  • 1
    That code contains syntax errors and won't compile (and has a whole bunch of other issues which mean the code doesn't make sense). I think you mistranscribed the interview question. – Quentin Jan 09 '20 at 11:59
  • @norbitrial — Since there is no constructor function in that code: no. – Quentin Jan 09 '20 at 12:00
  • 2
    NB: The "this inside function" question that this has been marked as a duplicate of is really unhelpful as it doesn't deal with anything resembling the case in this question at all. The question should remain closed for the time being though, as it won't compile, so `this` can't have a value. (There are a couple of different ways to fix the code that I could assume were intended to be asked about, but they have completely different answers to each other). – Quentin Jan 09 '20 at 12:09
  • See https://jsfiddle.net/eftjnr90/ for how the javascript code might look. – Adder Jan 09 '20 at 14:39

1 Answers1

0

this keyword refers to an object, that object which is executing the current bit of javascript code.

In other words, every javascript function while executing has a reference to its current execution context, called this. Execution context means here is how the function is called.

To understand this keyword, only we need to know how, when and from where the function is called, does not matter how and where function is declared or defined.

function bike() {
  console.log(this.name);
}

var name = "Ninja";
var obj1 = { name: "Pulsar", bike: bike };
var obj2 = { name: "Gixxer", bike: bike };

bike();           // "Ninja"
obj1.bike();      // "Pulsar"
obj2.bike();      // "Gixxer"
Hemanth
  • 91
  • 1
  • 8
  • While that is true in the most simple case for using `this`, the example in this question is **not** the most simple case. As I pointed out in a comment, the code in the question won't even compile. Even if it did, then it isn't calling a function on an object in the way you demonstrate in your attempt to answer it. – Quentin Jan 09 '20 at 12:02
  • You should also describe what `this` means in a jQuery function call. – Adder Jan 09 '20 at 12:18