[英]JavaScript two objects - overriding each other
我正在尝试学习JavaScript中的面向对象编程。 因此,我可能在做错事。
我有一个JS函数(类):
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
我不明白这里出了什么问题。 如果这两个是两个不同的对象,那么为什么会引起问题。 我在这里添加了完整的代码。
提前致谢。
User.prototype.getEmpId() {
return this.empId;
}
应该
User.prototype.getEmpId = function () {
return this.empId;
}
每次实例化User对象时,User.prototype.getEmpId将被覆盖。 prototype属性在所有实例之间共享。
然后该怎么做:
User.prototype.getEmpId = function() {
return this.empId;
}
检查这个小提琴:
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
现在回到示例共享中面临的问题。 我发现您在每次实例化User
对象时都在User.prototype
对象本身上设置属性/值。 相反,您应该在User
每个instances
进行设置。 以下是更新的jsfiddle,它可以工作:
完成的主要更改:
第一,
formUserObjectFromObject.call(this);//calling with reference of this
和,
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;
}
}
}
希望能帮助理解!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.