Solidity - 函式修飾符



函式修飾符用於修改函式的行為。例如,為函式新增一個先決條件。

首先,我們建立一個有或無引數的修飾符。

contract Owner {
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}

函式體插入在修飾符定義中出現特殊符號“_;”的地方。因此,如果在呼叫此函式時滿足修飾符條件,則執行該函式,否則丟擲一個異常。

請參閱以下示例 −

pragma solidity ^0.5.0;

contract Owner {
   address owner;
   constructor() public {
      owner = msg.sender;
   }
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}
contract Register is Owner {
   mapping (address => bool) registeredAddresses;
   uint price;
   constructor(uint initialPrice) public { price = initialPrice; }
   
   function register() public payable costs(price) {
      registeredAddresses[msg.sender] = true;
   }
   function changePrice(uint _price) public onlyOwner {
      price = _price;
   }
}
廣告
© . All rights reserved.