I was asked the following question at an OA. I did not figure it out and I would like to know the solution to this question.
I was asked to console Thank you for Logging in Dan
:
var Wrap = (function(){
function User(name){
this.name = name;
}
var d = function(){
console.log('1');
return "Thank you for Logging in" + this.name;
};
User.prototype.thankForLoggingln = d;
return User;
})();
I figured that out that Wrap
returns User, which make Wrap
equals to User
. And if I do Wrap('Dan')
, this.name
will change to Dan
.
The question is, I cannot access to thankForLoggingln
. I have tried Wrap.()thankForLoggingln()
and things like this, I got reference errors. Any idea?
Your understanding of
I figured that out that Wrap returns User, which make Wrap equals to User
is correct. But when you say Wrap('Dan')
, in this case this
would refer to the Global object. In case, you are running this on a browser, then you can access your name variable by window.name
. You must call the function with the new
keyword, so that a new object would be created and this
would refer to the newly created object and User
would be it's constructor. In this case it would have access to the thankForLoggingln
function.
So the correct way of doing it would be
var user = new Wrap('Dan');
user.thankForLoggingln();
For more information read constructor and You Don't Know JS