|  | 
|  | 1 | +--- | 
|  | 2 | +title: 面向对象编程 vs 函数式编程 | 
|  | 3 | +date: 2024-11-10T13:40:57Z | 
|  | 4 | +slug: post-25 | 
|  | 5 | +author: chaseFunny:https://github.com/chaseFunny | 
|  | 6 | +tags: ["编码规范","基础知识"] | 
|  | 7 | +--- | 
|  | 8 | + | 
|  | 9 | +## 什么是面向对象与函数式编程? | 
|  | 10 | + | 
|  | 11 | +编程范式主要分为面向对象编程(Object-Oriented Programming,简称OOP)和函数式编程(Functional Programming,简称FP)。理解这两种编程范式,有助于我们选择合适的方式来解决问题,提高代码的可维护性和扩展性 | 
|  | 12 | + | 
|  | 13 | +### 面向对象编程 | 
|  | 14 | + | 
|  | 15 | +它是属于 **命令式编程** ,命令式编程还包含了过程式编程。面向对象编程是一种以对象为中心的编程范式,它将数据和操作数据的方法组织在对象中,特点如下: | 
|  | 16 | + | 
|  | 17 | +- 封装:将数据和方法捆绑在一个对象内部,对外只暴露必要的信息,通过访问控制保护数据的完整性 | 
|  | 18 | +- 继承:允许类重用其他类的代码,通过不断抽象,减少重复代码 | 
|  | 19 | +- 多态:同一个接口可以有多种实现,对象可以根据上下文采取不同的形态来提高代码的灵活性和可扩展性 | 
|  | 20 | + | 
|  | 21 | +### 函数式编程 | 
|  | 22 | + | 
|  | 23 | +它属于声明式编程,它还包含了逻辑式编程、数学编程及响应式编程等方式。函数式编程是一种以函数为核心的编程范式,例如我们经常听到的”函数是一等公民“,它的特点如下: | 
|  | 24 | + | 
|  | 25 | +- 纯函数:相同输入始终产生相同输出,没有副作用,不依赖外部状态 | 
|  | 26 | +- 不可变性:数据一旦创建就不可变,修改数据就返回新的数据 | 
|  | 27 | +- 高阶函数:函数可以作为参数和返回值 | 
|  | 28 | + | 
|  | 29 | +# 面向对象编程体验 | 
|  | 30 | + | 
|  | 31 | +下面我们使用面向对象编程思想来做一个 Todo List | 
|  | 32 | + | 
|  | 33 | +代码我放到代码小抄:https://www.codecopy.cn/post/81sxun | 
|  | 34 | + | 
|  | 35 | +因为是一个 HTML 代码,大家可以直接运行调试,我们来看一下 JavaScript 代码部分: | 
|  | 36 | + | 
|  | 37 | +```js | 
|  | 38 | +      // Todo 项类 | 
|  | 39 | +      class TodoItem { | 
|  | 40 | +        constructor(id, text, completed = false) { | 
|  | 41 | +          this.id = id; | 
|  | 42 | +          this.text = text; | 
|  | 43 | +          this.completed = completed; | 
|  | 44 | +        } | 
|  | 45 | + | 
|  | 46 | +        toggle() { | 
|  | 47 | +          this.completed = !this.completed; | 
|  | 48 | +        } | 
|  | 49 | +      } | 
|  | 50 | + | 
|  | 51 | +      // Todo 列表管理类 | 
|  | 52 | +      class TodoList { | 
|  | 53 | +        constructor() { | 
|  | 54 | +          this.todos = []; | 
|  | 55 | +          this.loadFromLocalStorage(); | 
|  | 56 | +        } | 
|  | 57 | + | 
|  | 58 | +        addTodo(text) { | 
|  | 59 | +          const id = Date.now(); | 
|  | 60 | +          const todo = new TodoItem(id, text); | 
|  | 61 | +          this.todos.push(todo); | 
|  | 62 | +          this.saveToLocalStorage(); | 
|  | 63 | +          return todo; | 
|  | 64 | +        } | 
|  | 65 | + | 
|  | 66 | +        removeTodo(id) { | 
|  | 67 | +          this.todos = this.todos.filter((todo) => todo.id !== id); | 
|  | 68 | +          this.saveToLocalStorage(); | 
|  | 69 | +        } | 
|  | 70 | + | 
|  | 71 | +        toggleTodo(id) { | 
|  | 72 | +          const todo = this.todos.find((todo) => todo.id === id); | 
|  | 73 | +          if (todo) { | 
|  | 74 | +            todo.toggle(); | 
|  | 75 | +            this.saveToLocalStorage(); | 
|  | 76 | +          } | 
|  | 77 | +        } | 
|  | 78 | + | 
|  | 79 | +        saveToLocalStorage() { | 
|  | 80 | +          localStorage.setItem("todos", JSON.stringify(this.todos)); | 
|  | 81 | +        } | 
|  | 82 | + | 
|  | 83 | +        loadFromLocalStorage() { | 
|  | 84 | +          const stored = localStorage.getItem("todos"); | 
|  | 85 | +          if (stored) { | 
|  | 86 | +            const parsedTodos = JSON.parse(stored); | 
|  | 87 | +            this.todos = parsedTodos.map((todo) => new TodoItem(todo.id, todo.text, todo.completed)); | 
|  | 88 | +          } | 
|  | 89 | +        } | 
|  | 90 | +      } | 
|  | 91 | + | 
|  | 92 | +      // Todo 应用类 | 
|  | 93 | +      class TodoApp { | 
|  | 94 | +        constructor() { | 
|  | 95 | +          this.todoList = new TodoList(); | 
|  | 96 | +          this.render(); | 
|  | 97 | +        } | 
|  | 98 | + | 
|  | 99 | +        addTodo() { | 
|  | 100 | +          const input = document.getElementById("todoInput"); | 
|  | 101 | +          const text = input.value.trim(); | 
|  | 102 | + | 
|  | 103 | +          if (text) { | 
|  | 104 | +            this.todoList.addTodo(text); | 
|  | 105 | +            input.value = ""; | 
|  | 106 | +            this.render(); | 
|  | 107 | +          } | 
|  | 108 | +        } | 
|  | 109 | + | 
|  | 110 | +        removeTodo(id) { | 
|  | 111 | +          this.todoList.removeTodo(id); | 
|  | 112 | +          this.render(); | 
|  | 113 | +        } | 
|  | 114 | + | 
|  | 115 | +        toggleTodo(id) { | 
|  | 116 | +          this.todoList.toggleTodo(id); | 
|  | 117 | +          this.render(); | 
|  | 118 | +        } | 
|  | 119 | + | 
|  | 120 | +        render() { | 
|  | 121 | +          const todoListElement = document.getElementById("todoList"); | 
|  | 122 | +          todoListElement.innerHTML = ""; | 
|  | 123 | + | 
|  | 124 | +          this.todoList.todos.forEach((todo) => { | 
|  | 125 | +            const li = document.createElement("li"); | 
|  | 126 | +            li.className = `todo-item ${todo.completed ? "completed" : ""}`; | 
|  | 127 | + | 
|  | 128 | +            const checkbox = document.createElement("input"); | 
|  | 129 | +            checkbox.type = "checkbox"; | 
|  | 130 | +            checkbox.checked = todo.completed; | 
|  | 131 | +            checkbox.onclick = () => this.toggleTodo(todo.id); | 
|  | 132 | + | 
|  | 133 | +            const text = document.createElement("span"); | 
|  | 134 | +            text.textContent = todo.text; | 
|  | 135 | + | 
|  | 136 | +            const deleteButton = document.createElement("button"); | 
|  | 137 | +            deleteButton.className = "delete-btn"; | 
|  | 138 | +            deleteButton.textContent = "删除"; | 
|  | 139 | +            deleteButton.onclick = () => this.removeTodo(todo.id); | 
|  | 140 | + | 
|  | 141 | +            li.appendChild(checkbox); | 
|  | 142 | +            li.appendChild(text); | 
|  | 143 | +            li.appendChild(deleteButton); | 
|  | 144 | +            todoListElement.appendChild(li); | 
|  | 145 | +          }); | 
|  | 146 | +        } | 
|  | 147 | +      } | 
|  | 148 | + | 
|  | 149 | +      // 初始化应用 | 
|  | 150 | +      const todoApp = new TodoApp(); | 
|  | 151 | + | 
|  | 152 | +      // 添加回车键支持 | 
|  | 153 | +      document.getElementById("todoInput").addEventListener("keypress", function (e) { | 
|  | 154 | +        if (e.key === "Enter") { | 
|  | 155 | +          todoApp.addTodo(); | 
|  | 156 | +        } | 
|  | 157 | +      }); | 
|  | 158 | +``` | 
|  | 159 | + | 
|  | 160 | +这里我们创建了三个类,分别是:TodoItem 类:表示一个待办事项,包含ID、文本和完成状态。提供切换完成状态的方法;TodoList 类:管理待办事项的列表,提供添加、删除和切换完成状态的方法。数据持久化到本地存储等方法。TodoApp 类:负责UI渲染和用户交互,包括添加、删除和切换待办事项的完成状态。我们通过抽象这个功能为三个类,每个类来实现单一的逻辑,然后外层调用里层的类,**就像洋葱一样,把复杂的逻辑封装在了里面**。使用者无需关心怎么实现的,只需要知道怎么使用就好了 | 
|  | 161 | + | 
|  | 162 | +# 函数式编程体验 | 
|  | 163 | + | 
|  | 164 | +完整代码还在这里:https://www.codecopy.cn/post/81sxun | 
|  | 165 | + | 
|  | 166 | +```js | 
|  | 167 | + // 创建新的 todo 项 | 
|  | 168 | +      const createTodo = (text) => ({ | 
|  | 169 | +        id: Date.now(), | 
|  | 170 | +        text, | 
|  | 171 | +        completed: false, | 
|  | 172 | +      }); | 
|  | 173 | + | 
|  | 174 | +      // 切换 todo 完成状态 | 
|  | 175 | +      const toggleTodo = (todo) => ({ | 
|  | 176 | +        ...todo, | 
|  | 177 | +        completed: !todo.completed, | 
|  | 178 | +      }); | 
|  | 179 | + | 
|  | 180 | +      // 过滤删除指定 todo | 
|  | 181 | +      const removeTodoById = (todos, id) => todos.filter((todo) => todo.id !== id); | 
|  | 182 | + | 
|  | 183 | +      // 添加新的 todo | 
|  | 184 | +      const addTodo = (todos, text) => [...todos, createTodo(text)]; | 
|  | 185 | + | 
|  | 186 | +      // 切换指定 todo 的状态 | 
|  | 187 | +      const toggleTodoById = (todos, id) => todos.map((todo) => (todo.id === id ? toggleTodo(todo) : todo)); | 
|  | 188 | + | 
|  | 189 | +      // 本地存储操作 | 
|  | 190 | +      const storage = { | 
|  | 191 | +        save: (todos) => localStorage.setItem("todos", JSON.stringify(todos)), | 
|  | 192 | +        load: () => JSON.parse(localStorage.getItem("todos") || "[]"), | 
|  | 193 | +      }; | 
|  | 194 | + | 
|  | 195 | +      // 渲染函数 | 
|  | 196 | +      const renderTodos = (todos, handlers) => { | 
|  | 197 | +        const todoList = document.getElementById("todoList"); | 
|  | 198 | +        todoList.innerHTML = ""; | 
|  | 199 | + | 
|  | 200 | +        const createTodoElement = (todo) => { | 
|  | 201 | +          const li = document.createElement("li"); | 
|  | 202 | +          li.className = `todo-item ${todo.completed ? "completed" : ""}`; | 
|  | 203 | + | 
|  | 204 | +          const checkbox = document.createElement("input"); | 
|  | 205 | +          checkbox.type = "checkbox"; | 
|  | 206 | +          checkbox.checked = todo.completed; | 
|  | 207 | +          checkbox.onchange = () => handlers.onToggle(todo.id); | 
|  | 208 | + | 
|  | 209 | +          const text = document.createElement("span"); | 
|  | 210 | +          text.textContent = todo.text; | 
|  | 211 | + | 
|  | 212 | +          const deleteButton = document.createElement("button"); | 
|  | 213 | +          deleteButton.className = "delete-btn"; | 
|  | 214 | +          deleteButton.textContent = "删除"; | 
|  | 215 | +          deleteButton.onclick = () => handlers.onDelete(todo.id); | 
|  | 216 | + | 
|  | 217 | +          li.appendChild(checkbox); | 
|  | 218 | +          li.appendChild(text); | 
|  | 219 | +          li.appendChild(deleteButton); | 
|  | 220 | +          return li; | 
|  | 221 | +        }; | 
|  | 222 | + | 
|  | 223 | +        todos.forEach((todo) => { | 
|  | 224 | +          todoList.appendChild(createTodoElement(todo)); | 
|  | 225 | +        }); | 
|  | 226 | +      }; | 
|  | 227 | + | 
|  | 228 | +      // 应用状态管理 | 
|  | 229 | +      const createTodoApp = () => { | 
|  | 230 | +        let todos = storage.load(); | 
|  | 231 | + | 
|  | 232 | +        const updateState = (newTodos) => { | 
|  | 233 | +          todos = newTodos; | 
|  | 234 | +          storage.save(todos); | 
|  | 235 | +          render(); | 
|  | 236 | +        }; | 
|  | 237 | + | 
|  | 238 | +        const handlers = { | 
|  | 239 | +          onAdd: (text) => { | 
|  | 240 | +            if (text.trim()) { | 
|  | 241 | +              updateState(addTodo(todos, text)); | 
|  | 242 | +            } | 
|  | 243 | +          }, | 
|  | 244 | +          onToggle: (id) => { | 
|  | 245 | +            updateState(toggleTodoById(todos, id)); | 
|  | 246 | +          }, | 
|  | 247 | +          onDelete: (id) => { | 
|  | 248 | +            updateState(removeTodoById(todos, id)); | 
|  | 249 | +          }, | 
|  | 250 | +        }; | 
|  | 251 | + | 
|  | 252 | +        const render = () => renderTodos(todos, handlers); | 
|  | 253 | + | 
|  | 254 | +        // 初始渲染 | 
|  | 255 | +        render(); | 
|  | 256 | + | 
|  | 257 | +        return handlers; | 
|  | 258 | +      }; | 
|  | 259 | + | 
|  | 260 | +      // 初始化应用 | 
|  | 261 | +      const app = createTodoApp(); | 
|  | 262 | + | 
|  | 263 | +      // 事件监听设置 | 
|  | 264 | +      document.getElementById("addButton").addEventListener("click", () => { | 
|  | 265 | +        const input = document.getElementById("todoInput"); | 
|  | 266 | +        app.onAdd(input.value); | 
|  | 267 | +        input.value = ""; | 
|  | 268 | +      }); | 
|  | 269 | + | 
|  | 270 | +      document.getElementById("todoInput").addEventListener("keypress", (e) => { | 
|  | 271 | +        if (e.key === "Enter") { | 
|  | 272 | +          const input = document.getElementById("todoInput"); | 
|  | 273 | +          app.onAdd(input.value); | 
|  | 274 | +          input.value = ""; | 
|  | 275 | +        } | 
|  | 276 | +      }); | 
|  | 277 | +``` | 
|  | 278 | + | 
|  | 279 | + 通过上面的代码,可以看到所有的逻辑都是使用函数完成的,通过纯函数和不可变性提高了代码的可预测性和可维护性。但是相比较面向对象编程的代码可能没有那么清晰 | 
|  | 280 | + | 
|  | 281 | + | 
|  | 282 | + | 
|  | 283 | +# 面向对象 VS 函数式 | 
|  | 284 | + | 
|  | 285 | +通过上面的代码,可以很直观的看到他们各自的优缺点,我们再对比总结一下: | 
|  | 286 | + | 
|  | 287 | +- 代码组织方式上:OOP 是基于对象,把数据和对应的行为封装在一起,通过类来管理代码;FP 是围绕函数来得到新的数据,数据和行为是分开的 | 
|  | 288 | +- 状态管理上:OOP 是对象内部进行维护,通过类的方法来更新对象状态,并且状态变化可能会导致副作用;FP是通过函数返回新的数据(状态),来强调的数据不可变性 | 
|  | 289 | +- 代码复用上:OOP 就是通过继承来实现代码复用;FP 就是通过组合函数来实现代码复用 | 
|  | 290 | +- 使用场景上:OOP 适合有明确的对象和对应行为的系统,需要复杂状态管理;FP 适合业务开发,并发编程,数据转换和计算 | 
|  | 291 | + | 
|  | 292 | +我们再来看一下前端中知名的库使用的编程范式,Vue2.x 就是基于面向对象编程,React 18之前的类组件也是基于面向对象编程,每一个组件其实都是一个对象。但是在 React 18之后,就改为了函数式编程和自定义hooks,是因为类组件中复用逻辑非常麻烦,需要借助 HOC(高阶组件),但是高阶组件会创建没有必要的组件树,会产生嵌套地狱,调试也变得困难,知道 自定义 hooks 的出现,让 React 组件复用逻辑变得非常简单,我觉得最重要的点是 类组件 并没有使用到 class 的特性,我们并没有使用到封装、继承等等特性。 | 
|  | 293 | + | 
|  | 294 | +技术没有银弹,哪种编程方式都有弊端,只有都熟练使用才能在遇到问题选择出合适的编码方式,写出优雅的代码 | 
|  | 295 | + | 
|  | 296 | +# 参考 | 
|  | 297 | + | 
|  | 298 | +1)为什么面向对象和函数式编程都有问题:https://github.com/AlexiaChen/YinWangBak/blob/master/%E4%B8%BA%E4%BB%80%E4%B9%88%E8%AF%B4%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B%E5%92%8C%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E9%83%BD%E6%9C%89%E9%97%AE%E9%A2%98.md | 
|  | 299 | + | 
|  | 300 | + | 
|  | 301 | + | 
|  | 302 | +--- | 
|  | 303 | +此文自动发布于:<a href="https://github.com/coderPerseus/blog/issues/25" target="_blank">github issues</a> | 
0 commit comments