var result = num.calculate('+');
var num = { x: 12, y: 3, calculate: function(operation) { var fn; switch (operation) { case '+': fn = function() { return this.x + this.y }; break; case '-': fn = function() { return this.x - this.y }; break; default: fn = function() {}; } return fn(); } }
x
和y
属性存在于调用上下文中,num
对象-引用num.x
,或在调用函数时使用fn.call(num)
,以便函数内部的this
引用num
对象: var num = {
x: 12,
y: 3,
calculate: function(operation) {
var fn;
switch (operation) {
case '+':
fn = function() {
return this.x + this.y
};
break;
case '-':
fn = function() {
return this.x - this.y
};
break;
default:
fn = function() {};
}
return fn.call(num);
}
}
risult = num.calculate('+');
console.log(risult);
您还可以使用箭头函数,以便从外部范围继承this
,例如fn = () => this.x + this.y
:var num = { x: 12, y: 3, calculate: function(operation) { var fn; switch (operation) { case '+': fn = () => this.x + this.y break; case '-': fn = () => this.x - this.y; break; default: fn = function() {}; } return fn(); } } risult = num.calculate('+'); console.log(risult);
但是switch
非常冗长,并且很容易出错。如何使用由operation
索引的对象(以及使用正确的拼写以防止错误,请使用result
,而不是risult
):const fns = { '+': () => num.x + num.y, '-': () => num.x - num.y, }; var num = { x: 12, y: 3, calculate: operation => { const fn = fns[operation] || (() => null); return fn(); } }; const result = num.calculate('+'); console.log(result);