0

I'm just learning JS callback function, in this code when I separately run seniorOrJunior method it's working just fine but when I called it through callback function It shows the following error!

let date = new Date();

let john = {
    id : 0123,
    name : 'Not Set',
    joinYear : 2015,
    category : 'Not Set',
    position : 'Software Engineer',

    fullname : function (firstname, lastname) {
        this.name = 'firstname' + ' ' + 'lastname';
    },

    checkLength : function() {
        date.getFullYear() - this.joinYear;
    },

    seniorOrJunior : function () {
        if (this.checkLength() < 2) {
            this.category = 'Junior';
        } else {
            this.category = 'Senior';
        }
    }
}

function salary(callback) {

    callback();

    if (john.category === seniorOrJunior) {
        console.log('Your salary is 40k');
    } else if (john.category === seniorOrJunior)  {
        console.log('Your Salary is 25k');
    }

}

salary(john.seniorOrJunior);

this code is showing this error : enter image description here

Mohib
  • 429
  • 1
  • 9
  • 25
  • you need to call salary method with this argument : `salary(john.seniorOrJunior.bind(john));`. The callback references `this` keyword, and in the global context we have `this` === window, as window.checkLength is not defined you have this error – Olivier Boissé Aug 23 '17 at 11:49
  • 1
    or use `callback.call(john);` instead of just `callback()` – xander Aug 23 '17 at 11:49
  • Add return to checkLength function... – Adrian Aug 23 '17 at 11:50
  • Oh! Thanks! Solved ! :) – Mohib Aug 23 '17 at 12:03
  • Would you please take a look at this : https://hastebin.com/ibigevoqoj.js – Mohib Aug 23 '17 at 12:25
  • https://hastebin.com/ibigevoqoj.js This code also works, but when I reorder the callback function parameter like : callback(name, callback) ; Then it show this error : TypeError: callback.call is not a function – Mohib Aug 23 '17 at 12:26

0 Answers0