This is an interview questions, Asked to write a Man class to let the following code can run properly:
var me =new Man();
//method one:
me.attr("fullname", "tom");
//method two:
me.fullname = "jim";
console.info("my name is:" + me.attr("fullname"));
/*------[result is]------
my name is:tom
------------------*/
my answer is:
var Man=function(){
};
Man.prototype.attr=function(attr,val){
if(val){
this[attr]=val;
}
else{
return this[attr];
}
}
The results of my code to run is:
/*------[result is]------
my name is:jim
------------------*/
who can help me? thanks
You could make a second dictionary:
You could use a closed variable:
You could use a closed
fullnamevariable, and ignore everything except'fullname':You could also return
"tom"every single time, or pretend all the attributes are"fullname", or both. You could ROT13 property names before assigning them. You could add underscores. You could create a property instead that throws away values beginning with"j". The possibilities are limitless, actually.