Class Patterns [duplicate]

6

I'm not getting Portuguese literature, so I found an article in English that I did not quite understand the concept , could someone help me explaining the differences:

  • Write a Class with methods within the Class:

    function MyClass() {
        this.greet = function() {
            console.log('Hello!');
        };
    }
    var inst = new MyClass();
    inst.greet(); // => 'Hello!'
    
  • Write a Class with methods outside the Class:

    //Classe aqui
    function MyClass() {}
    
    //metodo usando prototype ( escrito fora da Classe )
    MyClass.prototype.greet = function() {
        console.log('Hello!');
    };
    var inst = new MyClass();
    inst.greet(); // => 'Hello!'
    
  • Apparently it would be the same thing, but the author of these examples says that the 1st code is inefficient, so I would like someone to explain to me if this is true and why, either for truth or false assertion of the author

        
    asked by anonymous 03.07.2015 / 15:25

    1 answer

    3

    With the first case, you will have a greet function for each instantiated variable. For example, if you instantiate two variables MyClass , each one will have its greet . Now with the second case, all instances share the same code for this function, so you only have the instance greet of MyClass and not each variable.

        
    03.07.2015 / 16:13