我已经创建了一个简短函数来设置和检索对象的值(> 按名称获取点),但我不确定我的解决方案是否真的那么聪明。
您建议进行哪些修改以完善此查询?
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 构造函数
,例如:
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
关于javascript:设置属性或返回值? (简单的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6689892/