To understand clearly about the this
statement, you must understand that it represents the current "scope" inside the function.
When you declare :
function Test() {
this.clientData = {
....
};
}
this
represents the current scope of the Test
function. That's why, when you will do var test = new Test();
, you will be able to use test.clientData
and then get access to data you set in the initialization of your object.
Now, inside your clientData
property of your test
object, you have a setUserName
(I recommend you to name it setFullName
) which is again a function (JavaScript is function scoped). So if we look at your code :
function Test() {
this.clientData = {
fullName: "Not Set",
setFullName: function(firstName, lastName) {
/*
* `this` represents the scope of the `setFullName` function,
* and not the scope of the `Test` function
*/
this.fullName = firstName + " " + lastName;
}
};
}
So the trick is to store this
in a variable in the top level, because JavaScript is function scoped, the variable will be available for every function inside the scope. So now we can do that :
function Test() {
var self = this;
self.clientData = {
fullName: "Not Set",
setFullName: function(firstName, lastName) {
self.clientData.fullName = firstName + " " + lastName;
}
};
}
I recommend you, to split your data and your method in a different way. Now you put everything in a clientData
object that add some complexity to your app. You can separate the stored values (name, age, any storage information) and the methods that will interact with the data.
I suggest something like that :
function Person() {
var self = this;
self.fullName = "Not Set"
self.setFullName = function(firstName, lastName) {
self.fullName = firstName + " " + lastName;
};
}
var john = new Person();
john.setFullName("John", "Doe");
console.log("john.fullName : " + john.fullName); // Display : John Doe
var bruce = new Person()
bruce.setFullName("Bruce", "Wayne");
console.log("bruce.fullName : " + bruce.fullName); // Display : Bruce Wayne
This way you have a much easier code to read and a much easier code to execute. After, it is up to you to organize and design your object logic the way you want to.
Hope it helps.