How do I create a class in Javascript?

前端 未结 3 1533
無奈伤痛
無奈伤痛 2021-02-03 14:36

This is what I got so far, and it\'s not working at all :( all the variables are null in my player class and update never gets called.

I mean a programming class, not a

3条回答
  •  星月不相逢
    2021-02-03 14:47

    According to this article, there are three ways to define a class in JavaScript:

    1 Using a function

    Example:

     function Apple (type) {
         this.type = type;
         this.color = "red";
         this.getInfo = getAppleInfo;
     }
    
     function getAppleInfo() {
         return this.color + ' ' + this.type + ' apple';
     }
    
    
     var apple = new Apple('macintosh');
     apple.color = "reddish";
     alert(apple.getInfo());
    

    2 Using JSON

     var apple = {
         type: "macintosh",
         color: "red",
         getInfo: function () {
             return this.color + ' ' + this.type + ' apple';
         }
     }
    
    
     apple.color = "reddish";
     alert(apple.getInfo());
    

    3 Singleton using a function

     var apple = new function() {
         this.type = "macintosh";
         this.color = "red";
         this.getInfo = function () {
             return this.color + ' ' + this.type + ' apple';
         };
     }
    
    
     apple.color = "reddish";
     alert(apple.getInfo());
    

提交回复
热议问题