Xuyue Shi
Xuyue Shi

Reputation: 333

Prototype a function to another function JavaScript?

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?

Upvotes: 0

Views: 111

Answers (4)

Neha Tawar
Neha Tawar

Reputation: 705

Try following will surely work.

Wrap.prototype.thankForLoggingln() 

The function gets invoked immediately,after trying Wrap it gave me this output. So the

ƒ User(name){
    this.name = name;
  }

Basically it followed the clean inheritance using prototype.So Wrap.prototype gives both method as well as constructor user.Either access using new keyword or using prototype. Check following:

About Prototypes

Upvotes: 0

GSSwain
GSSwain

Reputation: 6143

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

Upvotes: 1

Patrick Hund
Patrick Hund

Reputation: 20256

You can create an instance of User by instantiating Wrap like so:

var user = new Wrap('Dan');

With that instance, you can then call the thankYouForLoggingIn method like so:

var message = user.thankYouForLoggingIn();
console.log(message);

So your code example is really just a fancy way of creating a class.

Upvotes: 0

traktor
traktor

Reputation: 19356

User.prototype.thankForLoggingln = d;

means user objects created using User as a constructor inherit `thankForLogging in.

So

console.log( new Wrap(" Dan").thankForLoggingln());

does the trick. There should be a console.log of '1' immediately prreceeding it.

Two addditional traps were set:

  • thankForLogginln end in lower case L fofollowed by 'n'. Spellng it as 'thankForLogginIn` takes debugging.
  • The name has to be supplied with a leading space to print correctly.

Upvotes: 1

Related Questions