IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Instanciation d'objet et portée de variable


Sujet :

JavaScript

  1. #1
    Membre très actif
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Mai 2014
    Messages
    227
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur de jeux vidéo
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2014
    Messages : 227
    Par défaut Instanciation d'objet et portée de variable
    Bonjour à tous, depuis peu je me suis mis au Javascript et aujourd'hui je rencontre un souci très gênant.
    Voici le code qui me pose problème :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
     
     
    var Input = (function()
    {
      function Input(canvasName)//take canvasName instead of canvas
      {
        this.__canvasName           = 0;
        this.__mousePosition        = 0;
        this.__mouseButtonLeftDown  = 0;
        this.__mouseButtonRightDown = 0;
        this.__mouseClick           = 0;
        this.__canvasName           = canvasName;
        this.__mousePosition        = new Vector2f(50,0);
        this.init();
      }
     
      Input.prototype.init = function()
      {
        console.log("INIT:" + this.__canvasName);
        document.getElementById(this.__canvasName).addEventListener('mousemove',this.update_mousePosition);
      }
     
      Input.prototype.update_mousePosition = function(event)
      {
        console.log("UPDATE:"+this.__canvasName);
     
        var rect = $('canvas')[0].getBoundingClientRect();
        this.__mousePosition = new Vector2f(event.clientX - rect.left ,event.clientY - rect.top);
      }
     
      Input.prototype.mousePosition = function()
      {
        return this.__mousePosition;
      }
     
     
     
      return Input;
    }());
    Input["__class"] = "Input";
    Si je créer un nouvelle objet comme suit :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    var canvasName = 'canvas';
    var input = new Input(canvasName); // or Object.create
    Et que j’exécute mon code, alors la console m'écrit ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    INIT:canvas
    UPDATE:undefined
    J'ai l'impression que quand je fais this.__canvasName dans la fonction update_mousePosition, je fait référence à l'objet update_mousePosition et non l'objet Input.
    Pourtant la fonction init elle, fonctionne. Je ne vois aucune différence entre les deux mise à part que l'autre fonction reçoit des event...

    Merci de votre aide

  2. #2
    Membre Expert
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    2 910
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 2 910
    Par défaut
    Salut,

    Je crois que tu as raison, j'ai fait un test...

    J'avais déjà vu cette question il me semble mais je ne retrouve pas le cours en question...

    Une solution : "var self = this;" ---> remplace ta fonction init() par :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    Input.prototype.init = function () {
            var self = this;
            console.log("INIT:" + this.__canvasName);
            document.getElementById(this.__canvasName).addEventListener('mousemove', function (event) {
                self.update_mousePosition(event);
     
            });
        };

  3. #3
    Membre très actif
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Mai 2014
    Messages
    227
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur de jeux vidéo
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2014
    Messages : 227
    Par défaut
    Merci beaucoup ! Dans une autre class j'avais fait [var that = this;] mais je n'avais pas penser à faire ça ici, encore merci

    Je vous partage mon code si ça intéresse, il permet de regrouper quelque événement souris sur un canvas :

    mouseInput.js
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
     
    var MouseInput = (function()
    {
      function MouseInput(canvasName)
      {
        this.__canvasName             = 0;
        this.__mousePosition          = 0;
        this.__mouseButtonLeftDown    = 0;
        this.__mouseButtonRightDown   = 0;
        this.__mouseButtonMiddleDown  = 0;
        this.__mouseClick             = 0;
        this.__canvasName             = canvasName;
        this.__mousePosition          = new Vector2f(0,0);
        this.init();
      }
     
      MouseInput.prototype.init = function()
      {
        var that    = this;
        var canvas  = document.getElementById(this.__canvasName);
     
        canvas.addEventListener('mousemove', function(event){that.update_mousePosition(event);});
        canvas.addEventListener('mousedown', function(event){that.update_mouseButtonDown(event);});
        canvas.addEventListener('mouseup', function(event){that.update_mouseButtonUp(event);});
      }
     
      MouseInput.prototype.update_mousePosition = function(event)
      {
        var rect = $(this.__canvasName)[0].getBoundingClientRect();
        this.__mousePosition = new Vector2f(event.clientX - rect.left ,event.clientY - rect.top);
      }
     
      MouseInput.prototype.update_mouseButtonDown = function(event)
      {
        if( event.button === 0)
          this.__mouseButtonLeftDown = true;
        if( event.button === 1)
          this.__mouseButtonMiddleDown = true;
        if( event.button === 2)
          this.__mouseButtonRightDown = true;
      }
     
      MouseInput.prototype.update_mouseButtonUp = function(event)
      {
        if( event.button === 0)
          this.__mouseButtonLeftDown = false;
        if( event.button === 1)
          this.__mouseButtonMiddleDown = false;
        if( event.button === 2)
          this.__mouseButtonRightDown = false;
      }
     
      MouseInput.prototype.position = function()           {return this.__mousePosition;}
      MouseInput.prototype.isButtonLeftDown = function()   {return this.__mouseButtonLeftDown;}
      MouseInput.prototype.isButtonMiddleDown = function() {return this.__mouseButtonMiddleDown;}
      MouseInput.prototype.isButtonRightDown = function()  {return this.__mouseButtonRightDown;}
     
      return MouseInput;
    }());
    MouseInput["__class"] = "MouseInput";
    Exemple d'utilisation
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    var canvasName = "nomDuCanvas";
    var input = new MouseInput(canvasName);
     
    ...
     
    if( input.isButtonLeftDown() )
        alert("Clic gauche à la position : " + input.position.toString());

  4. #4
    Membre Expert
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    2 910
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 2 910
    Par défaut
    Merci.

    Pourquoi cette ligne : MouseInput["__class"] = "MouseInput"; ?

    Et c'est quoi Vector2f();

  5. #5
    Membre très actif
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Mai 2014
    Messages
    227
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur de jeux vidéo
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2014
    Messages : 227
    Par défaut
    Pour ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    var __extends = (this && this.__extends) || function (d, b) {
        for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };


    Et Vector2f c'est ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
     
     
    var Vector2f = (function () {
        function Vector2f(x, y) {
            var _this = this;
            if (((typeof x === 'number') || x === null) && ((typeof y === 'number') || y === null)) {
                var __args = Array.prototype.slice.call(arguments);
                this.__x = 0;
                this.__y = 0;
                this.__x = 0;
                this.__y = 0;
                (function () {
                    _this.__x = x;
                    _this.__y = y;
                })();
            }
            else if (((x != null && x instanceof Vector2f) || x === null) && y === undefined) {
                var __args = Array.prototype.slice.call(arguments);
                var vector_1 = __args[0];
                this.__x = 0;
                this.__y = 0;
                this.__x = 0;
                this.__y = 0;
                (function () {
                    _this.__x = new Number(vector_1.x()).valueOf();
                    _this.__y = new Number(vector_1.y()).valueOf();
                })();
            }
            else if (x === undefined && y === undefined) {
                var __args = Array.prototype.slice.call(arguments);
                this.__x = 0;
                this.__y = 0;
                this.__x = 0;
                this.__y = 0;
            }
            else
                throw new Error('invalid overload');
        }
        Vector2f.prototype.equals = function (vector) {
            if (this.__x === vector.x() && this.__y === vector.y())
                return true;
            return false;
        };
        Vector2f.prototype.x = function () {
            return this.__x;
        };
        Vector2f.prototype.y = function () {
            return this.__y;
        };
        Vector2f.prototype.setX = function (x) {
            this.__x = x;
        };
        Vector2f.prototype.setY = function (y) {
            this.__y = y;
        };
        Vector2f.prototype.addX = function (x) {
            this.__x += x;
        };
        Vector2f.prototype.addY = function (y) {
            this.__y += y;
        };
        Vector2f.prototype.subX = function (x) {
            this.__x -= x;
        };
        Vector2f.prototype.subY = function (y) {
            this.__y -= y;
        };
        Vector2f.prototype.mulX = function (x) {
            this.__x *= x;
        };
        Vector2f.prototype.mulY = function (y) {
            this.__y *= y;
        };
        Vector2f.prototype.divX = function (x) {
            this.__x /= x;
        };
        Vector2f.prototype.divY = function (y) {
            this.__y /= y;
        };
        Vector2f.prototype.setValues = function (x, y) {
            this.__x = x;
            this.__y = y;
        };
        Vector2f.prototype.set = function (value) {
            this.__x = value.x();
            this.__y = value.y();
        };
        Vector2f.prototype.bigger = function () {
            return this.__x > this.__y ? this.__x : this.__y;
        };
        Vector2f.prototype.smaller = function () {
            return this.__x > this.__y ? this.__y : this.__x;
        };
        Vector2f.prototype.sum = function () {
            return this.__x + this.__y;
        };
        Vector2f.prototype.biggerthan = function (vector) {
            return (this.__x > vector.x() && this.__y > vector.y());
        };
        Vector2f.prototype.smallerthan = function (vector) {
            return (this.__x < vector.x() && this.__y < vector.y());
        };
        Vector2f.prototype.morePositiveValueThan = function (vector) {
            return this.__x + this.__y > vector.x() + vector.y();
        };
        Vector2f.prototype.moreNegativeValueThan = function (vector) {
            return this.__x + this.__y < vector.x() + vector.y();
        };
        Vector2f.prototype.swap = function (vector) {
            var x = this.__x;
            var y = this.__y;
            this.set(vector);
            vector.setValues(x, y);
        };
        Vector2f.prototype.isBetween = function (first, second) {
            if (this.__x > first.x() && this.__x < second.x())
                if (this.__y > first.y() && this.__y < second.y())
                    return true;
            return false;
        };
        Vector2f.prototype.awayfrom = function (vector, distance) {
            return Math.sqrt(Math.pow(this.__x - vector.x(), 2) + Math.pow(this.__y - vector.y(), 2)) > distance;
        };
        Vector2f.prototype.normalize = function (vector) {
            return Math.sqrt(Math.pow(vector.x(), 2) + Math.pow(vector.y(), 2));
        };
        Vector2f.prototype.shoot = function (endpos) {
            var shoot = new Vector2f(endpos.x() - this.__x, endpos.y() - this.__y);
            var norme = this.normalize(shoot);
            shoot.divide$float(norme);
            return shoot;
        };
        Vector2f.prototype.randValueBetween = function (value) {
            if (value.x() <= this.__x && value.y() <= this.__y)
                return new Vector2f(value.x() + Math.random() * (this.__x - value.x()), value.y() + Math.random() * (this.__y - value.y()));
            if (value.x() <= this.__x && value.y() >= this.__y)
                return new Vector2f(value.x() + Math.random() * (this.__x - value.x()), this.__y + Math.random() * (value.x() - this.__y));
            if (value.x() >= this.__x && value.y() <= this.__y)
                return new Vector2f(this.__x + Math.random() * (value.x() - this.__x), value.y() + Math.random() * (this.__y - value.y()));
            return new Vector2f(this.__x + Math.random() * (value.x() - this.__x), this.__y + Math.random() * (value.y() - this.__y));
        };
        Vector2f.prototype.scaledCopy = function (value) {
            return new Vector2f(this.__x * value, this.__y * value);
        };
        Vector2f.prototype.divide$Vector2f = function (value) {
            this.__x /= value.x();
            this.__y /= value.y();
        };
        Vector2f.prototype.divide$float = function (value) {
            this.__x /= value;
            this.__y /= value;
        };
        Vector2f.prototype.divide$float$float = function (x, y) {
            this.__x /= x;
            this.__y /= y;
        };
        Vector2f.prototype.divide = function (x, y) {
            if (((typeof x === 'number') || x === null) && ((typeof y === 'number') || y === null)) {
                return this.divide$float$float(x, y);
            }
            else if (((x != null && x instanceof Vector2f) || x === null) && y === undefined) {
                return this.divide$Vector2f(x);
            }
            else if (((typeof x === 'number') || x === null) && y === undefined) {
                return this.divide$float(x);
            }
            else
                throw new Error('invalid overload');
        };
        Vector2f.prototype.substract$Vector2f = function (value) {
            this.__x -= value.x();
            this.__y -= value.y();
        };
        Vector2f.prototype.substract$float = function (value) {
            this.__x -= value;
            this.__y -= value;
        };
        Vector2f.prototype.substract$float$float = function (x, y) {
            this.__x -= x;
            this.__y -= y;
        };
        Vector2f.prototype.substract = function (x, y) {
            if (((typeof x === 'number') || x === null) && ((typeof y === 'number') || y === null)) {
                return this.substract$float$float(x, y);
            }
            else if (((x != null && x instanceof Vector2f) || x === null) && y === undefined) {
                return this.substract$Vector2f(x);
            }
            else if (((typeof x === 'number') || x === null) && y === undefined) {
                return this.substract$float(x);
            }
            else
                throw new Error('invalid overload');
        };
        Vector2f.prototype.add$Vector2f = function (value) {
            this.__x += value.x();
            this.__y += value.y();
        };
        Vector2f.prototype.add$float = function (value) {
            this.__x += value;
            this.__y += value;
        };
        Vector2f.prototype.add$float$float = function (x, y) {
            this.__x += x;
            this.__y += y;
        };
        Vector2f.prototype.add = function (x, y) {
            if (((typeof x === 'number') || x === null) && ((typeof y === 'number') || y === null)) {
                return this.add$float$float(x, y);
            }
            else if (((x != null && x instanceof Vector2f) || x === null) && y === undefined) {
                return this.add$Vector2f(x);
            }
            else if (((typeof x === 'number') || x === null) && y === undefined) {
                return this.add$float(x);
            }
            else
                throw new Error('invalid overload');
        };
        Vector2f.prototype.multiply$Vector2f = function (value) {
            this.__x *= value.x();
            this.__y *= value.y();
        };
        Vector2f.prototype.multiply$float = function (value) {
            this.__x *= value;
            this.__y *= value;
        };
        Vector2f.prototype.multiply$float$float = function (x, y) {
            this.__x *= x;
            this.__y *= y;
        };
        Vector2f.prototype.multiply = function (x, y) {
            if (((typeof x === 'number') || x === null) && ((typeof y === 'number') || y === null)) {
                return this.multiply$float$float(x, y);
            }
            else if (((x != null && x instanceof Vector2f) || x === null) && y === undefined) {
                return this.multiply$Vector2f(x);
            }
            else if (((typeof x === 'number') || x === null) && y === undefined) {
                return this.multiply$float(x);
            }
            else
                throw new Error('invalid overload');
        };
        Vector2f.prototype.pow$Vector2f$float = function (v, p) {
            return new Vector2f((Math.pow(v.x(), p)), Math.pow(v.y(), p));
        };
        Vector2f.prototype.pow$Vector2f$Vector2f = function (v, p) {
            return new Vector2f((Math.pow(v.x(), p.x())), Math.pow(v.y(), p.y()));
        };
        Vector2f.prototype.pow = function (v, p) {
            if (((v != null && v instanceof Vector2f) || v === null) && ((p != null && p instanceof Vector2f) || p === null)) {
                return this.pow$Vector2f$Vector2f(v, p);
            }
            else if (((v != null && v instanceof Vector2f) || v === null) && ((typeof p === 'number') || p === null)) {
                return this.pow$Vector2f$float(v, p);
            }
            else
                throw new Error('invalid overload');
        };
        Vector2f.prototype.toString = function () {
            return new String(this.__x + ":" + this.__y);
        };
        return Vector2f;
    }());
    Vector2f["__class"] = "Vector2f";

  6. #6
    Membre Expert
    Homme Profil pro
    Inscrit en
    Octobre 2011
    Messages
    2 910
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Octobre 2011
    Messages : 2 910
    Par défaut
    Ah ben il y a du monde, il le fallait ce Vector2f pour que le code fonctionne...

    Sinon l'autre "truc" c'est pour faire des "extensions" genre class dérivées ?

  7. #7
    Membre très actif
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Mai 2014
    Messages
    227
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bas Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur de jeux vidéo
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2014
    Messages : 227
    Par défaut
    Il y a du monde ?
    -
    Oui mais tu peux le remplacer par un simple tableau genre {x:0,y:0}. Pour l'autre "truc" cela sert à faire de l'héritage, je n'ai pas fait cette chose, il n'y à que le Vector2f et MouseInput que j'ai codé

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [AC-2010] La portée des variables (et surout des objets)
    Par zooffy dans le forum VBA Access
    Réponses: 6
    Dernier message: 08/08/2017, 14h30
  2. Instancier un objet avec un nom contenu dans une variable
    Par paul59800 dans le forum Débuter avec Java
    Réponses: 12
    Dernier message: 06/11/2015, 17h24
  3. Variable utilisée pour instancier un objet
    Par Meta4 dans le forum Général Java
    Réponses: 7
    Dernier message: 20/06/2012, 01h02
  4. Réponses: 7
    Dernier message: 26/07/2010, 15h25
  5. Réponses: 4
    Dernier message: 22/02/2010, 01h13

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo