修饰器,通过定义一个方法,使用该方法去修饰其他方法。
用个没有用修饰器的例子说明,onlyOwner 是一个校验地址是不是原来账号的地址的方法。
将该合约部署
contract Test {
address public owner;
uint256 public price;
constructor(){
owner = msg.sender;
}
function onlyOwner() public view{
require(
msg.sender == owner,
"Only seller can call this."
);
}
function setPrice(uint256 _price) public{
onlyOwner();
price = _price;
}
}
使用modifier
先定义一个 modifier
再在方法中修饰
contract ModifierTest {
address public owner;
uint256 public price;
constructor(){
owner = msg.sender;
}
modifier onlyOwner(){ // Modifier
require( msg.sender == owner, "Only Owner can call this." );
_;
}
function setPrice(uint256 _price) public
onlyOwner
{
price = _price;
}
}