Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this inside function

My question is:

function Foo() {    this.foo = "bar"; // <- What is "this" here? } 

From what I can tell it depends on how Foo is used, i.e. as a constructor or as a function. What can this be in different circumstances?

like image 346
Frank T. Icali Avatar asked Dec 26 '09 13:12

Frank T. Icali


Video Answer


1 Answers

The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object.

It's used in OOP code, to refer to the class/object the function belongs to For example:

function foo() {     this.value = 'Hello, world';      this.bar = function() {         alert(this.value);     } }  var inst = new foo(); inst.bar(); 

This alerts: Hello, world

You can manipulate which object this refers to by using the apply() or call() functions. (A very very handy feature at times)

var bar1 = new function() {     this.value = '#1'; } var bar2 = new function() {     this.value = '#2'; }  function foo() {     alert(this.value); }  foo.call(bar1); // Output: #1 foo.apply(bar2, []); // Output: #2 
like image 74
Atli Avatar answered Sep 18 '22 10:09

Atli