Search code examples
javascriptjquerynode.jsprototypeprototypejs

Call prototype another prototype in new object


This returns back thisFunction.weather.day() is undefined.. Why? Am i doing this correct?

 'use scrict';

    var thisFunction = function(){this.event(); };

    thisFunction.prototype.weather = function(){

        this.day = "Cloudy";

    };

    thisFunction.prototype.event = function(){

        console.log(thisFunction.weather().day);

    };

    var g = new thisFunction();

Im trying to call the weather function inside of event. As you can see at the bottom theres a new var g that equals new thisFunction(). If I call the weather function inside event thisFunction.prototype.weather().day is undefined. Why?


Solution

  • thisFunction is your constructor function.

    It does not have a .weather() method. So, thisFunction.weather is undefined and thisFunction.weather() is an error.

    The .weather() method is on the prototype which means its on instances of thisFunction, not on the constructor itself. So, in your code, you could do:

     g.weather()
    

    Or, inside of the .event() method, you could do this:

    thisFunction.prototype.event = function(){
    
        console.log(this.weather());
    };
    

    To make this.weather().day work, you'd have to return this from the .weather() method.

    thisFunction.prototype.weather = function(){
    
        this.day = "Cloudy";
        return this;
    
    };
    
    thisFunction.prototype.event = function(){
    
        console.log(this.weather().day);
    
    };