Class standards

Asked

Viewed 53 times

6

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

  1. Writing a Class with the methods within the Class:

    function MyClass() {
        this.greet = function() {
            console.log('Hello!');
        };
    }
    var inst = new MyClass();
    inst.greet(); // => 'Hello!'
    
  2. Writing a Class with methods outside of 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 look the same, but the author of these examples says that the first code is inefficient, so I would like someone to explain to me if this is true and why, either for truth or false statement of the author

  • I can say that if you want to create a private variable within Myclass, you won’t be able to access it if you prototype. In that case, the solution would be to declare it with this even.

  • See http://answall.com/q/65131 and http://answall.com/q/44191

1 answer

3


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.