0

I'm not really trying to build anything, just trying to understand this code

I'm so confused that I barely know how to ask this:

What is "this" referring to in these examples?

app.controller("TabController", function(){

this.tab = 1; //this should the property of the controller

this.setTab = function(tab){
  this.tab = tab; //this actually works to change the value of the property of the controller (this.tab = 1) why is it able to do that? Isn't "this" applied to the setTab property here?
  };

this.isSet = function(tab){
  return ( tab === this.tab); 
 > //same goes for this one as well, is "this.tab" here referencing the controllers tab property or the isSet property. I thought it would have been the isSet  
   };  
});

I'm just going through the angularjs tutorial

Shehary
  • 9,926
  • 10
  • 42
  • 71
  • 1
    Also read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this `this` will under no cicrumstance here refer to the method which is called – Jan Aug 08 '15 at 23:43
  • As usual I'm going to point you to:http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628?s=1|3.7878#13441628. But your question seems to imply that you've never programmed in an OO language before. In OO languages, `this` (or `self`) never refers to the method. It refers to the object the method belong to. So it never makes sense for `this` to refer to `setTab`. – slebetman Aug 09 '15 at 00:45

1 Answers1

0

this :

  • When the controller constructor function is called, this is the controller.
  • The 'this' reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope. Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.
  • 'This' a is used inside a function (let’s say function A) and it contains the value of the object that invokes function A. We need this to access methods and properties of the object that invokes function A, especially since we don’t always know the name of the invoking object, and sometimes there is no name to use to refer to the invoking object. Indeed, this is really just a shortcut reference for the “antecedent object”—the invoking object.

For further information & a basic example illustration of this property visit this link & regarding the difference between $scope vs this check this post! It really matters to make this clear !

Community
  • 1
  • 1
geokara1322
  • 60
  • 1
  • 9