Constructors in JavaScript objects

后端 未结 19 1990
夕颜
夕颜 2020-11-22 10:21

Can JavaScript classes/objects have constructors? How are they created?

19条回答
  •  不要未来只要你来
    2020-11-22 10:52

    Here we need to notice one point in java script, it is a class-less language however,we can achieve it by using functions in java script. The most common way to achieve this we need to create a function in java script and use new keyword to create an object and use this keyword to define property and methods.Below is the example.

    // Function constructor
    
       var calculator=function(num1 ,num2){
       this.name="This is function constructor";
       this.mulFunc=function(){
          return num1*num2
       };
    
    };
    
    var objCal=new calculator(10,10);// This is a constructor in java script
    alert(objCal.mulFunc());// method call
    alert(objCal.name);// property call
    
    //Constructors With Prototypes
    
    var calculator=function(){
       this.name="Constructors With Prototypes";
    };
    
    calculator.prototype.mulFunc=function(num1 ,num2){
     return num1*num2;
    };
    var objCal=new calculator();// This is a constructor in java script
    alert(objCal.mulFunc(10,10));// method call
    alert(objCal.name); // property call
    

提交回复
热议问题