0

I'm inheriting an object from the EASELJS library. To simplify the problem, I'm reducing the code into the minimal form.

I have a class:

this.TESTProg = this.TESTProg || {};

(function() {
    var _jsbutton = function(x, y, text, icon) {
        p.init(x, y, text, icon);
    };

    var p = _jsbutton.prototype = new createjs.Container();

    p.x = 0;
    p.y = 0;
    p.text = null;
    p.icon = null;

    p.init = function(x, y, text, icon) {
        this.x = 0 + x;
        this.y = 0 + y;
        this.text = "" + text;
        this.icon = null;
    };

    TESTProg._jsbutton = _jsbutton;
})();

Then I use it in another js object:

    var buttoncancel = new SJSGame._jsbutton(
            profileselConfig.cancelx,    //this is defined in another jsfile:
            profileselConfig.cancely,
            "cancel", "_cancel.png");

    console.log( buttoncancel.y );  //this gives 240

    var buttoncancel2 = new SJSGame._jsbutton(
            profileselConfig.cancelx,
            profileselConfig.cancely - 40,
            "cancel", "_cancel.png");

    console.log( buttoncancel.y );    //this gives 200
    console.log( buttoncancel2.y );   //this gives 200

    buttoncancel2.y = 100;
    console.log( buttoncancel.y );    //this now gives 200 (not changed by the second object)
    console.log( buttoncancel2.y );   //this now gives 100

The config file:

var _profileselConfig = function(){
    this.cancelx = 0;
    this.cancely = 240;
};

profileselConfig = new _profileselConfig();

And what am i doing wrong?

I'm already using 0 + to avoid passing the reference and it's not working. What should I do now? Any suggestions? Thanks.

  • Maybe check out [EaselJS: Can somebody explain the inheritance pattern used in demos?](http://stackoverflow.com/questions/18008421/easeljs-can-somebody-explain-the-inheritance-pattern-used-in-demos) – Bergi Aug 22 '13 at 17:43

1 Answers1

0

You should probably be calling this.init rather than p.init in your constructor.

When you call p.init, the this inside of init refers to the prototype. Thus, whenever you create an instance, your p.init call modifies the prototype for all _jsbutton objects.

That's why both buttons have the same x/y values: they both get their position from the same prototype, and the last-run constructor set the prototype values. When you set buttoncancel2.y outside of the constructor, you gave that instance its own y property, so it no longer used the shared prototype value.

If you call this.init in your constructor, then the this in init will refer to your newly-created instance. The instances will no longer use the shared prototype values for x, y, text, and icon.

Side note: "I'm already using 0 + to avoid passing the reference" -- this is not necessary, because primitive types are always copied.

apsillers
  • 112,806
  • 17
  • 235
  • 239