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

后端 未结 19 1451
庸人自扰
庸人自扰 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 07:54

    //new way using this and new
    function Persons(name) {
      this.name = name;
      this.greeting = function() {
        alert('Hi! I\'m ' + this.name + '.');
      };
    }
    
    var gee=new Persons("gee");
    gee.greeting();
    
    var gray=new Persons("gray");
    gray.greeting();
    
    //old way
    function createPerson(name){
     var obj={};
     obj.name=name;
     obj.greeting = function(){
     console.log("hello I am"+obj.name);
     }; 
      return obj;
    }
    
    var gita=createPerson('Gita');
    gita.greeting();

提交回复
热议问题