关于多个if else else if的优化

一段代码中,有很多的if else怎么去优化这个代码

var sayHello = function( personal ){
   if ( personal instanceof Li ){
      console.log( '嘿,你好' );
 }else if ( personal instanceof Dan ){
      console.log( '吃早饭了么' );
 }else if (personal instanceof Arthur){
       console.log('你今天看起来真漂亮')
       }
};

var Li = function(){};
var Dan = function(){};
var Arthur = function(){};

sayHello( new Li() ); // 嘿,你好

 sayHello( new Dan() ); // 吃早饭了么

 sayHello( new Arthur() ); // 你今天看起来真漂亮
阅读 5.2k
2 个回答

关于 JavaScript 中 if else 的问题可以参考吾辈的 JavaScript 避免使用 if-else 的方法
主要的思路是利用 策略模式 + 工厂函数 实现 状态机

这里也推荐一下吾辈的工具库 rx-util,里面实现了一个简单的 无限状态机 StateMachine

你的代码改造如下

import { StateMachine } from './StateMachine'

const stateMachine = StateMachine.getFactory()

class IBase {
  hello () {}
}

stateMachine.register(
  1,
  class Li extends IBase {
    hello () {
      return '嘿,你好'
    }
  }
)
stateMachine.register(
  2,
  class Dan extends IBase {
    hello () {
      return '吃早饭了么'
    }
  }
)
stateMachine.register(
  3,
  class Arthur extends IBase {
    hello () {
      return '你今天看起来真漂亮'
    }
  }
)

var sayHello = function (personal) {
  console.log(personal.hello())
}

sayHello(stateMachine.getInstance(1)) // 嘿,你好
sayHello(stateMachine.getInstance(2)) // 吃早饭了么
sayHello(stateMachine.getInstance(3)) // 你今天看起来真漂亮
function Base() {}
Base.prototype.sayHello = function() {
  console.log(this.helloStr)
}
var Li = function(){
  Base.call(this)
  this.helloStr = '嘿,你好'
}
Li.prototype = new Base()
var Dan = function() {
  Base.call(this)
  this.helloStr = '吃早饭了么'
}
Dan.prototype = new Base()
var Arthur = function(){
  Base.call(this)
  this.helloStr = '你今天看起来真漂亮'
}
Arthur.prototype = new Base()

var li = new Li()
li.sayHello()
var dan = new Dan()
dan.sayHello()
var arthur = new Arthur()
arthur.sayHello()

这样?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题