below is the solution which works for this algorithm but I didn’t understand why we should use this.fullName instead of fullName in the set functions ?
Per my understanding this keyword represents current object and it’s it logical to do this.fullName ?
Your code so far
var Person = function(firstAndLast) {
// Complete the method below and implement the others similarly
var fullName = firstAndLast;
this.getFirstName = function() {
return fullName.split(" ")[0];
};
this.getLastName = function() {
return fullName.split(" ")[1];
};
this.getFullName = function() {
return fullName;
};
this.setFirstName = function(name) {
fullName = name + " " + fullName.split(" ")[1];
};
this.setLastName = function(name) {
fullName = fullName.split(" ")[0] + " " + name;
};
this.setFullName = function(name) {
fullName = name;
};
};
var bob = new Person('Bob Ross');
bob.getFullName();
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.
If you used this.fullName, there would be no need for the getters & setters. You could change it from outside the object by using Person.fullName = "whatever"
By declaring it with var fullname, it contains that variable within the scope of Person. The outside world can’t see or modify fullName.
However, the getter & setter functions all have access to fullName thanks to closures, and through them it can be checked & modified.
It’s just an example of how you can exercise control over what happens within an object.
All of those are functions. And in the definition of Person they are attached to this because when you do new Person, this is going to be the instance of Person that you’ve just created, ie the calling context (you call the function getFullName in the context of that specific Person object, it’s attached specifically to that).
When the Person function is called, it creates a small environment, a closure, where any variables defined inside it also live. In this case there is a variable called fullName. It’s only accessible from inside the scope of the function, it is in effect private. But that object you’ve just created is also inside that scope, so those functions attached to the object can also access it.
As @lasjorg mentioned, it’s a bit strange that they’ve done it this way without explaining what’s happening. It’s a wee bit of an unusual way to do things, there are better ways; it works but it should explain why it works a bit better.