Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the difference between javascript methods assigned to properties of "this" vs. methods defined on the prototype?
    primarykey
    data
    text
    <p>I understand that the purpose of methods assigned as properties of "this" in a constructor is to make them privileged in that they can access private attributes and methods like this:</p> <pre><code>var Book = function(newFirst, newLast){ //private attributes var author_first = newFirst; var author_last = newLast; //public attributes this.puAuthor_first = newFirst; this.puAuthor_last = newLast; //public privileged methods (accessing private attributes) this.getAuthor = function() { return author_first + author_last; } } </code></pre> <p>but what's the difference to objects that inherit from Book compared to methods assigned to the prototype object like this: </p> <pre><code>Book.prototype.nonPrivilegedGetAuthor = function() { return this.puAuthor_first + this.puAuthor_last; } </code></pre> <p>?</p> <p>So my question is 2-fold:</p> <p>1) When this object is inherited from via Prototypical Inheritance, both getAuthor() and nonPrivilegedGetAuthor() are inherited, right? And the idea is that getAuthor() will be copied to the new object, whereas nonPrivilegedGetAuthor() will be available through the prototype chain, with the benefit of not being copied, right? What are the costs aside from not being able to access private members? </p> <p>2) What about Classical Inheritance? Specifically, will the public non-privileged method assigned as a property of the prototype object get inherited? What considerations should I be concerned with there? Without doing a few more things when you inherit, you'll basically have a gap in the prototype chain that skips over one object, right? We have to connect the child object's prototype chain to the Book--how do we do that? What do we do to properly inherit, and what pitfalls can happen if we don't?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload