我正在尝试为变量res创建方法。预期的结果将是res.add.wood('100')
。这将使木材数量增加100个。res.get.wheat()
会得到小麦的数量。
资源是“木头”、“小麦”、“黄金”、“肉”,动作是“get”、“set”、“add”、“sub”。我并不打算把它们都定义如下:
var resources = ['wood', 'wheat', 'gold', 'meat'];
var actions = ['get', 'set', 'add', 'sub'];
var res;
function res.get.wood() {
//
}
function res.set.wood() {
//
}
// 6 more to define.....
我正在寻找一种让它更快的方法。
下面的代码使我能够使用res.get()
、res.set()
、res.add()
和res.sub()
var res = ['get', 'set', 'add', 'sub'];
res.forEach(function(arrayElement) {
res[arrayElement] = function() {
alert(arrayElement)
}
});
我需要另一个循环,我已经尝试了以下方法,但它不起作用:
res.forEach(function(arrayElement) {
['get', 'set', 'add', 'sub'].forEach(function(arrayInnerElement) {
res[arrayElement][arrayInnerElement] = function() {
alert(arrayInnerElement);
}
});
});
发布于 2016-08-13 19:16:44
我建议这样做:
var resources = { 'wood': 50, 'wheat': 100, 'gold': 0, 'meat': 50 };
var resourceManager = (function(resources) {
function Resource(amount) {
this.amount = amount || 0;
}
Resource.prototype.get = function() {
return this.amount;
};
Resource.prototype.set = function(amount) {
this.amount = amount;
};
Resource.prototype.add = function(amount) {
this.amount += amount;
};
Resource.prototype.sub = function(amount) {
this.amount -= amount;
};
var o = {};
Object.keys(resources).forEach(function(resource) {
o[resource] = new Resource(resources[resource]);
});
return o;
}(resources));
var res = resourceManager;
console.log(res.wood.get()); // 50
res.wood.set(10);
console.log(res.wood.get()); // 10
res.wood.add(5);
res.wood.sub(2);
console.log(res.wood.get()); // 13
发布于 2016-08-13 19:20:16
如果您有一个现有函数来处理所有操作(例如,执行API调用),并且只想要一个更好的接口,则可以使用ES5 Array.prototype.reduce创建res
对象。
function resource_action(resource, action, amount) {
console.log(resource, action, amount);
};
var resources = ['wood', 'wheat', 'gold', 'meat'];
var actions = ['get', 'set', 'add', 'sub'];
var res = resources.reduce(function(res, r) {
res[r] = actions.reduce(function(act, a) {
act[a] = function(amount) {
return resource_action(r, a, amount);
};
return act;
}, {})
return res;
}, {});
res.gold.add(10);
发布于 2016-08-13 19:16:57
只需将prototype对象设置为您的新对象,并在那里定义它。
function Item () {
this.get = function () {alert("got me");}
this.set = function () {}
this.add = function () {}
this.sub = function () {}
}
function Wood () {
}
Wood.prototype = new Item ();
那么你所要做的就是:
var newWoodItem = new Wood();
如果你需要重写其中一个方法。
function Wood () {
this.get = function () {alert("i am the new method.");}
}
https://stackoverflow.com/questions/38931992
复制相似问题