case语句中的Javascript箭头功能[重复]

问题描述 投票:-1回答:1
我想知道如何在case语句中实现箭头功能。如果我做类似的事情,请问如何获得例如15的“结果”?

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(); } }
javascript switch-statement arrow-functions
1个回答
0
投票
xy属性存在于调用上下文中,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);
© www.soinside.com 2019 - 2024. All rights reserved.