cocos creator require导出的对象

cocos creator 中require的用法,官方文档里面是有以下内容

一般我都会有一个 Game.js 的脚本作为总的控制脚本,假如我还有 Player.jsEnemy.jsMenu.js三个组件,那么他们的初始化过程是这样的:

// Game.js

const Player = require('Player');
const Enemy = require('Enemy');
const Menu = require('Menu');

cc.Class({
    extends: cc.Component,
    properties: {
        player: Player,
        enemy: Enemy,
        menu: Menu
    },

    onLoad: function () {
        this.player.init();
        this.enemy.init();
        this.menu.init();
    }
});

其中在 Player.jsEnemy.js 和 Menu.js 中需要实现 init 方法,并将初始化逻辑放进去。这样我们就可以保证 Player, Enemy 和 Menu 的初始化顺序。

但是如果这些脚本分散到各个节点上的时候,引用的时候是不对的,为了解决这个问题,做以下实验:

文件结构是:


我在Game脚本中require("Bird")

var bird = require('Bird');
cc.Class({
    extends: cc.Component,
    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        bird : {
            default : null,
            type    : cc.Node,
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        cc.log("bird is " + bird);
        //获得原型对象
        var birdComponent =  bird.prototype;
        //bird是一个构造函数
        var b1 = new bird();
        console.log("b1 is " + b1);
        //获得一个实例的原型对象
        console.log(Object.getPrototypeOf(b1));

    },

    start () {
        this.node.on('foobar',function(event){
            cc.log("已经接收到派送事件");
            //propagation 传播
            event.stopPropagation();
        });
    },

    update (dt) {
        cc.log("开始销毁节点");
        this.scheduleOnce(function(){
            if(cc.isValid(this.bird)){
                this.bird.rotation += dt * 30;
            }
        },3)
        cc.log(bird);
    },
});
var Shape = cc.Class({
    ctor : function(){
        //初始化时候父类构造器首先调用
        cc.log("Shape");
    }
});
var Rect = cc.Class({
    extends : Shape
});
var Square = cc.Class({
    extends : Rect,
    ctor    : function(){
        cc.log("Square");
    }
})
var square = new Square();

 在调试过程中发现 bird变量是一个函数,在js中函数都有一个原型对象,

function.prototype可以得到一个对象然后可以访问到他的方法

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值