Skip to main content
Participant
May 12, 2021
Answered

clone a function that increment the object instance name

  • May 12, 2021
  • 1 reply
  • 219 views

I want to clone a function that increment the object instance name:

 

 

var _this = this;


_this.rouge1.visible = false;
_this.BT1.on('mousedown', function () {
if (_this.rouge1.visible == false) {
_this.rouge1.visible = true;
} else {
_this.rouge1.visible = false;
}

});


_this.rouge2.visible = false;

_this.BT2.on('mousedown', function () {
if (_this.rouge2.visible == false) {
_this.rouge2.visible = true;
} else {
_this.rouge2.visible = false;
}

});

 

 

so as to have un new function with object name BT3, BT4, BT5.... and rouge3, rouge4, rouge5....

 

 

_this.rouge3.visible = false;

_this.BT3.on('mousedown', function () {
if (_this.rouge3.visible == false) {
_this.rouge3.visible = true;
} else {
_this.rouge3.visible = false;
}

});

 

......

without duplicating the code by hand

how to do ? Thanks for your help

    This topic has been closed for replies.
    Correct answer ClayUUID

    No, you don't want to "clone a function". What you want is a single function that can operate on variable instance names.

     

    function initButtons(id) {
    	var btn = _this["BT" + id];
    	btn.myRouge = _this["rouge" + id];
    	btn.myRouge.visible = false;
    	btn.on("mousedown", function(evt) {
    		evt.currentTarget.myRouge.visible = !evt.currentTarget.myRouge.visible;
    	});
    }
    
    initButtons(1);
    initButtons(2);
    initButtons(3);
    
    etc...
    

    1 reply

    ClayUUIDCorrect answer
    Legend
    May 12, 2021

    No, you don't want to "clone a function". What you want is a single function that can operate on variable instance names.

     

    function initButtons(id) {
    	var btn = _this["BT" + id];
    	btn.myRouge = _this["rouge" + id];
    	btn.myRouge.visible = false;
    	btn.on("mousedown", function(evt) {
    		evt.currentTarget.myRouge.visible = !evt.currentTarget.myRouge.visible;
    	});
    }
    
    initButtons(1);
    initButtons(2);
    initButtons(3);
    
    etc...