Overriding methods in Javascript

前端 未结 4 934
你的背包
你的背包 2020-12-10 03:52

I would like to know what is the difference between overriding methods with prototypes and without prototypes. Consider:

Example 1:

         


        
4条回答
  •  盖世英雄少女心
    2020-12-10 04:24

    As Arun mentioned in the first example you're creating sleep and eat functions for each new instance. In the second example there's only one sleep and eat function which is shared amongst all the instances.

    In this case the second method is better, but it's good to know when to use the first method and when to use the second. A little bit of theory first:

    Note: There are four kinds of variables in JavaScript - private, public, shared and static.

    Private variables are inaccessible outside of the function in which they are defined. For example:

    function f() {
        var x; // this is a private variable
    }
    

    Public variables are defined on the this object inside a function. For example:

    function f() {
        this.x; // this is a public variable
    }
    

    Shared variables are shared on the prototype of the function. For example:

    function f() {}
    
    f.prototype.x; // this is a shared variable
    

    Static variables are properties of the function itself. For example:

    function f() {}
    
    f.x; // this is a static variable
    

    Most often it's best to declare the methods of a constructor function as shared methods since all instances of the constructor share them. However if your method needs to access a private variable then it must be declared as a public method itself.

    Note: This is my own nomenclature. Not many JavaScript programmers adhere to it. Others seem to follow Douglas Crockford's nomenclature: http://javascript.crockford.com/private.html

    To know more about prototypal inheritance in JavaScript read the following answer: https://stackoverflow.com/a/8096017/783743

提交回复
热议问题