Solidity之Modifier(还有那个酷酷的 _ )

pragma solidity ^0.4.11;

contract owned {
    function owned() public { owner = msg.sender; }
    address owner;

    // This contract only defines a modifier but does not use
    // it: it will be used in derived contracts.
    // The function body is inserted where the special symbol
    // `_;` in the definition of a modifier appears.
    // This means that if the owner calls this function, the
    // function is executed and otherwise, an exception is
    // thrown.
    定义了一个modifier但是没有使用,将在继承的合约中使用
    函数体将在特殊符号 _ 出现的位置被插入
    这里代表的是只有Owner调用这个方法时才会被执行,否则报错
    modifier onlyOwner {
        require(msg.sender == owner);
        _;
    }
}

contract mortal is owned {
    // This contract inherits the `onlyOwner` modifier from
    // `owned` and applies it to the `close` function, which
    // causes that calls to `close` only have an effect if
    // they are made by the stored owner.
    这个合约从owned继承了onlyOwner的modifier,应用在close方法上
    这将造成只有Owner才能调用close方法
    function close() public onlyOwner {
        selfdestruct(owner);
    }
}

contract priced {
    // Modifiers can receive arguments:
    modifiers可以接受参数
    modifier costs(uint price) {
        if (msg.value >= price) {
            _;
        }
    }
}

contract Register is priced, owned {
    mapping (address => bool) registeredAddresses;
    uint price;

    function Register(uint initialPrice) public { price = initialPrice; }

    // It is important to also provide the
    // `payable` keyword here, otherwise the function will
    // automatically reject all Ether sent to it.
    function register() public payable costs(price) {
        registeredAddresses[msg.sender] = true;
    }

    function changePrice(uint _price) public onlyOwner {
        price = _price;
    }
}

contract Mutex {
    bool locked;
    modifier noReentrancy() {
        require(!locked);
        locked = true;
        _;
        locked = false;
    }

    /// This function is protected by a mutex, which means that
    /// reentrant calls from within `msg.sender.call` cannot call `f` again.
    /// The `return 7` statement assigns 7 to the return value but still
    /// executes the statement `locked = false` in the modifier.
    function f() public noReentrancy returns (uint) {
        require(msg.sender.call());
        return 7;
    }
}

那么modifier在solidity中做的是什么工作呢?
答案就是给继承这个modifier修饰的function加上一个特定的约束,比如

  modifier isOwner() {
     if (msg.sender != owner) {
          throw;
      }
      _; // 继续执行余下的代码体(其实就是isOwner里的实际代码)
  }
  
  doSomething() isOwner {
    // 将会检查调用者是不是Owner
  
    // code
  }

你可能感兴趣的:(Solidity之Modifier(还有那个酷酷的 _ ))