Parent, Children, getParent() pointer troubles

I can’t understand this:

var HelloWorldLayer = cc.Layer.extend({
    sprite:null,
    ctor:function () {
        this._super();

        cc.log(this.getParent());//Get null <--------------- ?

        var closeItem = new cc.MenuItemImage(
            res.CloseNormal_png,
            res.CloseSelected_png,
            function () {
                cc.log("Menu is clicked!");
                this.whenRunAgain();                
            }, this);
    },
    
    whenRunAgain:function(){        
            cc.log(this.getParent());//This Works fine   <--------------- ?
    },    
});

var HelloWorldScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        var layer = new HelloWorldLayer();
        this.addChild(layer);
    }
});

When you create a CCNode, e.g. a CCLayer, it doesn’t get a parent until it has been added to another node using addChild(). A node will never have a parent while in ctor().

I believe onEnter() is when the node is added to the parent. (Technically I think onEnter() is when a node is added to the scene graph, but if the parent is part of the scene then onEnter() would be called when it’s added to its parent.)

1 Like

You got the reason, thanks :wink: