2011-07-14 57 views
2

我創建了一個短函數來設置和檢索對象的值(>按點名得分),但我不確定我的解決方案是否真的很聰明。javascript:設置屬性或返回值? (簡單的方法)

你推薦完善這個查詢的修改是什麼?

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) 
+0

我認爲這完全是正確的) –

+0

我只會改變方法;-)我不喜歡它設置一個值,並命名爲'getPoints'函數的名稱。我會改變它(像jQuery函數)到'points'。一個參數= get,兩個參數= set – Fender

回答

1

[編輯]以前的答案是錯誤的:沒有提到的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 
1

我會爲getter和setter創建一個不同的函數。 一個函數調用getPoints還設置點不作任何SENCE和會混淆PPL :)

1

我看到的唯一問題是,points值被覆蓋每次調用getpoints時間,即:

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

這個名字也令人困惑。礦verison是:

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