区块链学堂(29):Modifiers
Modifiers can be used to easily change the behaviour of functions, for example to automatically check a condition prior to executing the function. They are inheritable properties of contracts and may be overridden by derived contracts. 引用自here
一个使用modifier的例子
pragma solidity 0.4.10;
contract demo {
uint public deadline;
function demo() {
deadline = now;
deadline += 10;
}
modifier afterDeadline {
if (now <= deadline) throw;
_;
}
function f() afterDeadline returns (string s) {
return "afterDeadline";
}
function g() afterDeadline returns (uint n) {
n = 100;
}
}
- 从上面的例子中可以看到,我们先在构造函数中,给deadline赋予一个值。在当前时间+10s
- 然后modifier afterDeadline, 必须要当前时间过了10s,才不抛出异常
- 然后我们可以在很多方法中使用modifier afterDeadline(). 从而使得代码非常简洁和美观。
另一个例子,给上一节中的代币合约中添加Modifier
Step 1: 首先定义一个modifier
modifier onlyMinter {
if (msg.sender != minter) throw;
_;
}
Step 2: 新增一个新的 function mint2()
function changeMinter(address _to) onlyMinter {
minter = _to;
}
对比一下之前的function mint()
function mint(address receiver, uint amount) {
if (msg.sender != minter) throw;
balances[receiver] += amount;
}
很明显可以看到,通过modifier,在执行主函数之前,先进行一个条件检查。通过modifier,可以使代码变得很美。
Step 3: 添加个function changeMinter()
function changeMinter(address _to) onlyMinter {
minter = _to;
}
上一节代码加上Step 1-3后的完整代码如下:
pragma solidity 0.4.7;
contract Coin {
address public minter;
mapping (address => uint) public balances;
event Sent(address from, address to, uint amount);
function Coin() {
minter = msg.sender;
}
function mint(address receiver, uint amount) {
if (msg.sender != minter) throw;
balances[receiver] += amount;
}
function send(address receiver, uint amount) {
if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Sent(msg.sender, receiver, amount);
}
//对挖矿使用onlyOwner
modifier onlyMinter {
if (msg.sender != minter) throw;
_;
}
function mint2(address receiver, uint amount) onlyMinter {
balances[receiver] += amount;
}
function changeMinter(address _to) onlyMinter {
minter = _to;
}
}
原文:http://www.ethchinese.com/?p=1122
QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin
获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网
还没有评论,来说两句吧...