Can't access method from another method?

I have trouble understanding what you can access and where.
I have Tests script with prototype method initialize where i want to bind method1 on click
I get the error Uncaught ReferenceError: method1 is not defined

how to define methods so i can access them this way

var Tests = pc.createScript('tests');

Tests.attributes.add("root", { type: 'entity' });
Tests.attributes.add("create", { type: 'entity' });


// initialize code called once per entity
Tests.prototype.initialize = function () {

    let app = this.app;
    this.create.button.on('click', function (event) {

        method1();
        //method2();

    });
};

// add callback methods that will trigger on click
Tests.prototype.method1 = function () {

    console.log("method2");
    console.log("button clicked");
    let root = this.root;

    for (let i = 0; i < 100; i++) {
        var templateAsset = this.app.assets.get(68783156);
        var instance = templateAsset.resource.instantiate();
        var pos = new pc.Vec3(0 + i * 10, 0, 0);
        instance.setLocalPosition(pos);
        root.addChild(instance);

        let scriptInstance = instance.script.reelElementController.Test();
    }
};

Tests.prototype.method2 = function () {
    console.log("method2");
};

Hi @mirkoni,

In JavaScript you need to specify the context when declaring anonymous methods. You can either do so using bind(this) or PlayCanvas provides a convenience argument on events that can be used for this.

    this.create.button.on('click', function (event) {

        method1();
        //method2();

    }, this);

Observe the change on the last line.

1 Like

ok, great it works.
i need to use this.method1(); though

thanks!

1 Like