Solidity 没名字的function(){...}作用

官方解释:

这个叫做fallback function,当有人 1. 只发送以太币给合约而不带任何输入数据;2. 调用smart contract时调起了一个不存在的方法。会触发执行这个方法。

What is the deal with “function () { ... }” inside Solidity contracts? How can a function not have a name?

This function is called “fallback function” and it is called when someone just sent Ether to the contract without providing any data or if someone messed up the types so that they tried to call a function that does not exist.

The default behaviour (if no fallback function is explicitly given) in these situations is to just accept the call and do nothing. This is desireable in many cases, but should only be used if there is a way to pull out Ether from a contract.

If the contract is not meant to receive Ether with simple transfers, you should implement the fallback function as

function() { throw; }

this will cause all transactions to this contract that do not call an existing function to be reverted, so that all Ether is sent back.

Another use of the fallback function is to e.g. register that your contract received ether by using an event.

Attention: If you implement the fallback function take care that it uses as little gas as possible, because send() will only supply a limited amount.

如果不定义这个方法,所有被误转到这个合约上的以太币将被拒绝。

原文地址:https://www.cnblogs.com/huahuayu/p/8602590.html