Saturday, 17 August 2013

confused about this javascript behavior in closures

confused about this javascript behavior in closures

Geting a bit more into Javascript and OO programming but I'm not
understanding this behavior here of what why my ojbect (myUser cannot
access the property this.first_name as 'jon' and is instead undefined
(hilighted in red in screen shot at bottom). Here's the code fragment in
question:
function User(first_name, last_name){
this.first_name=first_name;
this.last_name=last_name;
}
// left in for completeness
User.prototype = {
constructor: User,
sayName: function(){
console.log("My Name: " + this.first_name + " and " +
this.last_name);
}
}
User.prototype.whoWhat = function(){
console.log(this.first_name + " I want to tell you now " +
Math.random());
}
var myUser=new User('jon', 'johnson');
myUser.sayName();
myUser.whoWhat();
setInterval(myUser.whoWhat, 3000);
And here is the console output:

No comments:

Post a Comment