cocos creator 中require的用法,官方文档里面是有以下内容
一般我都会有一个 Game.js
的脚本作为总的控制脚本,假如我还有 Player.js
, Enemy.js
, Menu.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.js
, Enemy.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可以得到一个对象然后可以访问到他的方法