聲明式和命令式


  1 . 聲明和命令式 (Declarative vs Imperative

  聲明和命令式是兩種編程范式。react是聲明式的,jquery那樣直接操作dom是命令式

Alright here’s a metaphor.

Declarative Programming is like asking your friend to draw a landscape. You don’t care how they draw it, that’s up to them.

Imperative Programming is like your friend listening to Bob Ross tell them how to paint a landscape. While good ole Bob Ross isn’t exactly commanding, he is giving them step by step directions to get the desired result.

      聲明式就像你告訴你朋友畫一幅畫,你不用去管他怎么畫的細節

  命令式就像按照你的命令,你朋友一步步把畫畫出來

     換言之

  • 命令式編程:命令“機器”如何去做事情(how),這樣不管你想要的是什么(what),它都會按照你的命令實現。
  • 聲明式編程:告訴“機器”你想要的是什么(what),讓機器想出如何去做(how)。

 2 . 來點代碼

     點擊一個按鈕,改變顏色

  命令式:

const container = document.getElementById(‘container’);
const btn = document.createElement(‘button’);
btn.className = ‘btn red’;
btn.onclick = function(event) {
 if (this.classList.contains(‘red’)) {
   this.classList.remove(‘red’);
   this.classList.add(‘blue’);
 } else {
   this.classList.remove(‘blue’);
   this.classList.add(‘red’);
 }
};
container.appendChild(btn);

   聲明式(react):

class Button extends React.Component{
  this.state = { color: 'red' }
  handleChange = () => {
    const color = this.state.color === 'red' ? 'blue' : 'red';
    this.setState({ color });
  }
  render() {
    return (<div>
      <button 
         className=`btn ${this.state.color}`
         onClick={this.handleChange}>
      </button>
    </div>);
  }
}

 

   注意到什么不一樣了么?

   react沒有去修改dom,只是聲明了頁面應該是什么樣子(根據不同的state).

   放到整個應用層面也是一樣的道理,我們更加需要關心的是整個應用和頁面的框架結構。

 

 

  參考鏈接:https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM