EOS 合约开发之 _self 关键字

yufei       5 年, 5 月 前       1096

_self 关键字,哦,不对,应该是类成员变量,充斥合约开发的方方面面。

_self 关键字是 <eosiolib/contract.hpp> 文件中的 eosio::contract 类的受保护的变量

protected:
  /**
   * The name of this contract
   *
   * @brief The name of this contract.
   */
  name _self;

那么,_self 代表的又是什么呢 ?

_self 是什么?

_self 类成员变量所代表的是 部署当前合约的账号

比如,假设存在 hello 合约,使用下面的命令部署,那么 _self 就是 hello

cleos set contract hello ../test -p hello@active
#                  -
#                  _self

如果使用下面的命令部署合约,那么 _self 就会 hi

cleos set contract hi ../test -p hi@active
#                  -
#                  _self

注意,这个部署合约的账号和 -p hi@active 是没有任何关系的,是 contract 关键字后面的那个

我们写一段代码来演示下

hello.cpp

#include<eosiolib/eosio.hpp>

class [[eosio::contract]] hello: eosio::contract {
public:
    using eosio::contract::contract;

    [[eosio::action]] void hi() {
        eosio::print("_self is: ");
        eosio::print(_self);
    }
};

EOSIO_DISPATCH(hello,(hi))

接着使用下面的命令来编译合约

eosio-cpp -o hello.wasm hello.cpp --abigen

最后使用下面的命令来部署合约

cleos set contract hello ../hello -p hello@active

我们使用下面的命令来调用下 hello 合约下的 hi 动作

cleos push action hello hi '[]' -p hello@active
executed transaction: 4fe589dec7d6df2ace6b4c1dc4f4b1cf189420cd6d243d5be9600c14c7a5933f  96 bytes  243 us
#         hello <= hello::hi                    ""
>> _self is: hello

我们使用另一个账号来部署一下

cleos set contract hi ../hello -p hi@active

然后在执行下 hi 合约下的 hi 动作

cleos push action hi hi '[]' -p hello@active
executed transaction: 7e080eb71551f44334f27f6ecab19ff90923a1d9a711b1fe4e62a313a679558b  96 bytes  228 us
#            hi <= hi::hi                       ""
>> _self is: hi

从上面的代码中可以看出,_self 无论如何都是部署当前合约的账号

目前尚无回复
简单教程 = 简单教程,简单编程
简单教程 是一个关于技术和学习的地方
现在注册
已注册用户请 登入
关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.