What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1450
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  伪装坚强ぢ
    2020-11-22 08:02

    Object Based Classes with Inheritence

    var baseObject = 
    {
         // Replication / Constructor function
         new : function(){
             return Object.create(this);   
         },
    
        aProperty : null,
        aMethod : function(param){
          alert("Heres your " + param + "!");
        },
    }
    
    
    newObject = baseObject.new();
    newObject.aProperty = "Hello";
    
    anotherObject = Object.create(baseObject); 
    anotherObject.aProperty = "There";
    
    console.log(newObject.aProperty) // "Hello"
    console.log(anotherObject.aProperty) // "There"
    console.log(baseObject.aProperty) // null
    

    Simple, sweet, and gets 'er done.

提交回复
热议问题