设置属性还是返回值?(简单的方式)

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

本文关键字:简单 方式 属性 返回值 设置      更新时间:2023-09-26

我创建了一个短函数来设置和检索对象(>按名称获取点)的值,但我不确定我的解决方案是否真的很聪明。

您建议如何修改以完善此查询?

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]之前的回答是错误的:没有提到getPoints("John")的不可能性

据我所知,你试图在一个函数中组合get和set。

您可以在这里使用Points constructor function,例如:

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

我将为getter和setter创建一个不同的函数。一个名为getPoints的函数也设置点,这没有任何意义,会混淆ppl:)

我看到的唯一问题是points的值每次调用getpoints时都会被覆盖,即:

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

这个名字也很容易混淆。我的版本是:

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'
}