开发者

javascript: Set Property or return Values? (simple way)

开发者 https://www.devze.com 2023-03-20 01:00 出处:网络
i\'ve created a short function to set and retrieve values from a object (> get points by name), but I\'m not sure if my solution is that really smart.

i've created a short function to set and retrieve values from a object (> get points by name), but I'm not sure if my solution is that really smart.

What 开发者_Go百科modifications do you recommend to perfect this query?

var points = {}; //global var

function getPoints() {

    var args = arguments, name;

    // set points or return them!

    if (typeof args[0] == 'object') {

        name = args[0].name;
        points = { name: args[0].points };

    } else {

        name = args[0];
        return points.name;
    }
}

  //set:
  getPoints(name: "John", points: 0)    //set points (0)
  getPoints(name: "Pamela", points: 2 ) //set points (2)

  //return:
  getPoints("John")    //returns > (0)
  getPoints("Pamela")  //returns > (2)


[edit] previous answer was wrong: didn't mention the impossibility of getPoints("John")

As far as I can see, you are trying to combine get and set in one function.

You may want to use a Points constructor function here, something like:

var Points = function(name,points){
   this.name = name || '';
   this.points = points || 0;
   if (!Points.prototype.get){
      var proto = Points.prototype;
      proto.get = function(label) {
         return this[label] || label
      };
      proto.set = function(){
        if (arguments.length === 2){
           this[arguments[0]] = arguments[1];
        } else if (/obj/i.test(typeof arguments[0])){
           var obj = arguments[0];
           for (var l in obj){
              if (obj.hasOwnProperty(l)){
               this[l] = obj[l];
              }
           }
        }
        return this;
      };
   }
}

var john = new Points('John',0), mary = new Points('Mary',2), pete = new Points;
pete.set({name:'Pete',points:12});
john.set('points',15);
//two ways to get a 'points' property
alert(john.get('points')+', '+pete.points); //=> 15, 12


I would create a different function for the getter and the setter. A function called getPoints that also sets points doesn't make any sence and would confuse ppl :)


The only problem I see is that the value of points gets overwritten every time you call getpoints i.e:

getPoints({name :"John", points: 0}); // points = {"John": 0}
getPoints({name:"Mein", points:1}); // points = {"Mein":1}

Also the name is confusing. Mine verison would be:

var points = {};
function getOrSetPoints(){
    if(typeof arguments[0] === "object"){
        points[arguments[0].name] = arguments[0].points;
    }
    else
        return points[arguments[0]] || arguments[0] + ' not set'
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号