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;
   }
}
广告