Object vs Class vs Function

后端 未结 7 1027
南方客
南方客 2020-11-28 20:03

I was wondering - what\'s the difference between JavaScript objects, classes and functions? Am I right in thinking that classes and functions are types of objects?

A

7条回答
  •  鱼传尺愫
    2020-11-28 20:24

    A Class in JS:

    function Animal(){  
    
        // Private property
        var alive=true;
    
        // Private method
        function fight(){ //... }   
    
        // Public method which can access private variables
        this.isAlive = function() { return alive; } 
    
        // Public property
        this.name = "Joe";
    }
    
    // Public method
    Animal.prototype.play = function() { alert("Bow wow!"); }
    
    // .. and so on
    

    Now when you create it's object

    var obj = new Animal();
    

    You can expect anything of this object as you would from objects in other language. Just the efforts to achieve it, was a bit different. You should also be looking at inheritance in JS.


    Getting back too your question, I'll reword it as:

    Class  : A representation of a set with common properties.
    object : One from the set with the same properties.
    
    
    var Class = function() {alert('bar');}; // A set of function which alert 'bar'
    var object = new Class();               // One of the functions who alert's 'bar'.
    

提交回复
热议问题