How do you define an OOP class in JavaScript?

前端 未结 7 695
野性不改
野性不改 2020-12-20 19:32

Based on my observation, the book that I am reading about JavaScript states that there\'s an OOP with JavaScript? It doesn\'t tell much about it, I mean it wasn\'t explained

7条回答
  •  执念已碎
    2020-12-20 20:14

    The following snippet may help you getting started with JavaScript's class-less, instance-based objects:

    function getArea() {  
       return (this.radius * this.radius * 3.14);  
    }  
    
    function getCircumference() {  
       var diameter = this.radius * 2;  
       var circumference = diameter * 3.14;  
       return circumference;  
    }
    
    function Circle(radius) {  
       this.radius = radius;  
       this.getArea = getArea;  
       this.getCircumference = getCircumference;  
    }
    
    var bigCircle = new Circle(100);  
    var smallCircle = new Circle(2);
    
    alert(bigCircle.getArea());            // displays 31400  
    alert(bigCircle.getCircumference());   // displays 618  
    alert(smallCircle.getArea());          // displays 12.56  
    alert(smallCircle.getCircumference()); // displays 12.56
    

    Example from: SitePoint - JavaScript Object-Oriented Programming

提交回复
热议问题