I have problem with create Object instance without reference.
I researched and found many people suggest using jQuery.extend
to create object without reference.
Refer: What is the most efficient way to deep clone an object in JavaScript?
But it not success in my case.
Here is my code JSBin
var MyModel = (function() {
MyModel = function() {};
var myModelObj = {
prop1: null,
prop2: {
sub1: null,
sub2: null
}
};
MyModel.prototype = {
getProp1: function() {
return myModelObj.prop1;
},
getSub1: function() {
return myModelObj.prop2.sub1;
},
getSub2: function() {
return myModelObj.prop2.sub2;
},
setProp1: function(val) {
myModelObj.prop1 = val;
},
setSub1: function(val) {
myModelObj.prop2.sub1 = val;
},
setSub2: function(val) {
myModelObj.prop2.sub2 = val;
},
getObj: function() {
return $.extend({}, myModelObj);
},
setObj: function(json_obj) {
myModelObj.prop1 = json_obj.prop1;
myModelObj.prop2.sub1 = json_obj.prop2.sub1;
myModelObj.prop2.sub2 = json_obj.prop2.sub2;
},
setParam: function(prop1, sub1, sub2) {
myModelObj.prop1 = prop1;
myModelObj.prop2.sub1 = sub1;
myModelObj.prop2.sub2 = sub2;
}
};
return MyModel;
}());
var model1 = new MyModel();
model1.setParam('prop1', 'sub1', 'sub2');
var model2 = new MyModel();
model2.setParam('clone-prop1', 'clone-sub1', 'clone-sub2');
console.log("object 1");
console.log(model1.getObj());
console.log("object 2");
console.log(model2.getObj());
My expected result is
model1 = {
prop1: 'prop1',
prop2: {
sub1: 'sub1',
sub2: 'sub2'
}
}
model2 = {
prop1: 'clone-prop1',
prop2: {
sub1: 'clone-sub1',
sub2: 'clone-sub2'
}
}
But actually, model1
and model2
have same data of model2
.
Can someone point me out where i made mistake?
=== Update ===
@arcyqwerty's solution help me solved create object without reference.
var MyModel = function() {
this.prop1 = null;
this.prop2 = {
sub1: null,
sub2: null
};
};
MyModel.prototype = {
getProp1: function() {
return this.prop1;
},
getSub1: function() {
return this.prop2.sub1;
},
getSub2: function() {
return this.prop2.sub2;
},
setProp1: function(val) {
this.prop1 = val;
},
setSub1: function(val) {
this.prop2.sub1 = val;
},
setSub2: function(val) {
this.prop2.sub2 = val;
},
getObj: function() {
return $.extend({}, this);
},
setObj: function(json_obj) {
this.prop1 = json_obj.prop1;
this.prop2.sub1 = json_obj.prop2.sub1;
this.prop2.sub2 = json_obj.prop2.sub2;
},
setParam: function(prop1, sub1, sub2) {
this.prop1 = prop1;
this.prop2.sub1 = sub1;
this.prop2.sub2 = sub2;
}
};
var model1 = new MyModel();
model1.setParam('prop1', 'sub1', 'sub2');
var model2 = new MyModel();
model2.setParam('clone-prop1', 'clone-sub1', 'clone-sub2');
console.log("object 1");
console.log(model1.getObj());
console.log("object 2");
console.log(model2.getObj());
But I also want use encapsulation
feature in OOP
. It means, we only get value object, property through get
function. Is it possible on Javascript
?
It explain why i have an object inside Model (but it reference on same object)
Thank you very much!