I am trying to learn Object Oriented Programming in JavaScript. Therefore, I may be wrong in what I am doing.
I have one JS function (class):
function User() {
//initiating object code goes here
}
//Functions
User.prototype.getEmpId = function() {
return this.empId;
}
var myUser = new User({'empid':'1'});
console.log(myUser.getEmpId()); //Returns 1
var mynewuser = new User({'empid':'2'});
console.log(myUser.getEmpId()); //Returns 2
console.log(mynewuser.getEmpId()); //Returns 2
I don't understand what is going wrong here. If these two are two different objects then why is it causing problem. I have added the complete code here .
Thanks in advance.
User.prototype.getEmpId() {
return this.empId;
}
should be
User.prototype.getEmpId = function () {
return this.empId;
}
User.prototype.getEmpId gets overridden each time you instantiate the User object. The prototype property is shared between all instances.
Then what to do:
User.prototype.getEmpId = function() {
return this.empId;
}
Check this fiddle :
http://jsfiddle.net/c5yhpav9/2/
function User(obj) {
//initiating object code goes here
this.empId=obj.empid;
}
//getEmpId now shared for all the instances of User
User.prototype.getEmpId=function() {
return this.empId;
}
var myUser = new User({'empid':'1'});
alert(myUser.getEmpId()); //Returns 1
var mynewuser = new User({'empid':'2'});
alert(myUser.getEmpId()); //Returns 1
alert(mynewuser.getEmpId()); //Returns 2
Now gettting back to the problem you are facing in your sample shared. I found that you are setting properties/values on the User.prototype
object itself each time a User
object is instantiated. Rather, you should set on each instances
of User
. Following is the updated jsfiddle which works:
Major Changes done:
first,
formUserObjectFromObject.call(this);//calling with reference of this
and,
function formUserObjectFromObject() {
//Will only be called for one object.
for (var userKey in arg[0]) {
switch(userKey) {
case "appId":
//Calling setAppId on this to set value of property
this.setAppId(arg[0][userKey]);
break;
case "empId":
this.setEmpId(arg[0][userKey]);
break;
case "firstName":
this.setFirstName(arg[0][userKey]);
break;
case "lastName":
this.setLastName(arg[0][userKey]);
break;
case "roleId":
this.setRoleId(arg[0][userKey]);
break;
case "emailId":
this.setEmailId(arg[0][userKey]);
break;
case "supervisorId":
this.setSupervisorId(arg[0][userKey]);
break;
default:
this.setCustom(userKey, arg[0][userKey]);
break;
}
}
}
Hope that helps to understand!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.