Search code examples
javascriptprototype

accessing function properties from one of its prototypes


I am sure that I misunderstand how i can access function properties from one of its prototypes . i may got -10 because of this question , but I truly need help in understanding why it always returns undefined

here is a reference

function lookup() {
  if (!(this instanceof lookup)) {
    return new lookup();
  }
  this.url = "/administration/lookups";
};
        
lookup.prototype.partial_create = () => {
  alert(this.url);
};
        
var lookup1 = function(){
  this.url = "/administration/lookups";
}
        
lookup1.prototype.makealert = ()=>{
  alert(this.url);
}
        
$(()=>{
  new lookup().partial_create();
  new lookup1().makealert();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Solution

  • It's because you've defined both the prototype methods as arrow functions - which behave differently from other functions with regard to the this keyword. (This indeed is the main point of using arrow functions in the first place - but they are misplaced here.) In particular (as you can read at the above link), arrow functions use the this of their enclosing scope - which here is the global scope. So this does not refer to your instance of lookup, but to the global object - hence this.url is just the global variable url, which (since you haven't defined such a variable) is undefined.

    To show the difference, run the below snippet - which is identical to yours with the arrow functions replaced by "regular" function declarations. This now works as you presumably intend:

    function lookup() {
      if (!(this instanceof lookup)) {
        return new lookup();
      }
      this.url = "/administration/lookups";
    };
            
    lookup.prototype.partial_create = function() {
      alert(this.url);
    };
            
    var lookup1 = function(){
      this.url = "/administration/lookups";
    }
            
    lookup1.prototype.makealert = function() {
      alert(this.url);
    }
            
    $(()=>{
      new lookup().partial_create();
      new lookup1().makealert();
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>