Making A Copy Of An Own Object Instead Of A Reference (updated Post, Different Q)
Solution 1:
You are right, you should be using the new
operator. Aside from that, it looks like you're trying to make this some type of factory hybrid. I suggest the following.
Use a Constructor Function
Include an optional configuration that you can use when creating the object.
varElement = function (initialConfig) {
if (initialConfig) {
this.create(initialConfig);
}
};
Add to the Prototype
All your shared Element
members should be part of the prototype.
Element.prototype = {
aArguments: {
"id" : false,
"name" : false,
"type" : false,
"title" : false,
"style" : false,
"action" : [],
"parent" : false,
"children" : {},
},
create:function ($aPassArguments) {
for (var prop in this.aArguments)
if (prop in $aPassArguments)
this.aArguments[prop] = $aPassArguments[prop];
return this;
},
append: function () {
$argList = arguments;
for ($i = 0; $i < $argList.length-1; $i++)
if (typeof $argList[$i]=="string")
this.setChild(this.importDB($argList[$i],true));
else
this.setChild($argList[$i]);
return this;
},
setChild: function($oChild) {
this.aArguments["children"][this.aArguments["children"].length-1]=$oChild;
},
getInfo: function($sKey) {
return this.aArguments[$sKey];
}
};
Examples
Your examples should now work as you expected. Notice that you can't call new Element.create()
as that would treat Element.create
as a constructor. Instead, pass your initial values into the constructor.
$set = newElement({"id": 1, "name" : "wrapper"}).
append(newElement({"id" : 3, "name" : "elm A"}));
alert($set.getInfo("name"));
Be Careful
You're not checking for own properties in your loops, omitting {}
, and I spotted at least one implied global. JavaScript will bite you if you're not careful. Consider using JSLint or JSHint to help you spot these problems.
Solution 2:
Your create function does not create any object, but rather changes on place the Element. aArguments
object. Any strange thing might follow.
Anyway, just go for a clean and simple prototypal inheritance scheme, do not use $, remember to always declare your vars, and keep things simple :
function Element(initialValues) {
this.id = this.prototype.id++;
this.name = null;
this.type = null;
this.title = null;
this.style = null;
this.action = [];
this.parent = null;
this.children = [];
for (var prop in initialValues)
if (this[prop] != undefined) this[prop] = initialValues[prop];
}
Element.prototype = {
append: function () {
for (var i = 0; i < arguments.length - 1; i++) {
var thisElement = arguments[i];
if (typeof thisElement == "string") this.setChild(this.importDB(thisElement, true));
elsethis.setChild(thisElement);
}
returnthis;
},
setChild: function (child) {
this.children.push(child);
returnthis;
},
getInfo: function (key) {
returnthis[Key];
},
id: 0
};
Post a Comment for "Making A Copy Of An Own Object Instead Of A Reference (updated Post, Different Q)"