here is my javascript:
function namespace(nameSpaceString){
var parts = nameSpaceString.split(".");
var parent = window;
var currentParent = '';
for(var i=0, len=parts.length; i<len;i++){
currentParent = parts[i];
parent[currentParent] = parent[currentParent] || {};
parent = parent[currentParent];
}
return parent;
}
abc = namespace('ns.abc');
abc.common = function(){
var arr = [];
setArr = function(v){
if(v){
arr.push(v);
}
}
getArr = function(){
return arr;
}
registerArr = function(ns){
if(ns){
for(var obj in ns){
if(obj.hasOwnProperty(getName)){
setArr(obj.getName());
}
}
}
}
return{
setArr : setArr,
getArr : getArr,
registerArr : registerArr
}
}
abc.form = function() {
var salutation = "Hi";
var name = '';
getSalutation = function(){
return salutation;
}
getName = function(){
return name;
}
setSalutation = function(s){
salutation = s;
}
setName = function(n){
name = n;
}
return{
getSalutation:getSalutation,
setSalutation:setSalutation,
getName : getName,
setName : setName
}
}
persons = namespace('ns.abc.persons');
persons.Dave = new abc.form();
persons.Dave.setName("Dave");
persons.Mitchell = new abc.form();
persons.Mitchell.setName('Mitchell');
persons.Mitchell.setSalutation('Howdy');
alert(persons.Mitchell.getSalutation()+":"+persons.Mitchell.getName());
commonObj = new abc.common();
commonObj.registerArr(persons);
alert("Registration:"+commonObj.getArr())
commonObj.setArr(persons.Dave.getName());
commonObj.setArr(persons.Mitchell.getName());
alert("Setter Methods:"+commonObj.getArr());
Here the Arr in Common when set by setter method works fine. But when I try to achieve the same by calling setter method form another member function -“registerArr” of the same object, it returns nothing.
How can I use setter method from within another member function?
You need to declare the variables holding the functions using
var.Since you aren’t declaring them, the variables become globals.
Therefore,
registerArrwill always use the functions from the last instance created, since that’s what’s in the global variables.Also, you’re misusing the
for…inloop.objiterates over the keys of every property in the object.To iterate over an array, use a normal
forloop.