【Modifier】
我們可以使用 modifier
來對一個函數進行補充敘述,或者在滿足 modifier
定義的特定條件後才執行函數的內容。在父合約定義 modifier
後,可以在子合約定義某些函式時進行調用。
此外,modifier
可以有參數也可以沒有參數。
pragma solidity ^0.8.11;
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;
}
}
modifier
內容最後的 _;
代表的是定義這些敘述為 modifier
。
這邊如果對繼承的內容還不熟悉可以先跳過,等到練熟繼承後再回來參考這裡的內容。
Last updated
Was this helpful?