Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When adding a function to a class' (this word being used lightly) prototype, all of the instances of that class will use the same function. On the other hand, if you define the function using the this keyword, you will only be defining for that instance. The benefit to prototypes is the fact that you can have one function which works for all instances of the class instead of defining a new function each time.</p> <p>As far as inheritance is concerned, I must defer to Douglas Crockford: <a href="http://www.crockford.com/javascript/inheritance.html" rel="nofollow">http://www.crockford.com/javascript/inheritance.html</a>. As far as making variables private, there is no way to truly make a variable private in a cross-browser way, but you can fake it. I have done it with jPaq's Color objects and others have written about it. Once again, I would suggest looking at what Douglas Crockford has to say: <a href="http://www.crockford.com/javascript/private.html" rel="nofollow">http://www.crockford.com/javascript/private.html</a>. Though my approach is a bit different, if you want to make members private, it is not impossible in JavaScript. Here is an example of how to implement private variables in a cross-browser fashion:</p> <pre><code>var Book = (function() { var key = {}; var Book = function(newFirst, newLast) { // Private variables stored in an object literal. var $ = { author_first : newFirst, author_last : newLast }; // Public privileged method for accessing private variables. this._ = function(aKey) { if(aKey === key) return $; throw new Error("The _() function must be called internally."); }; }; // Public accessor method. Book.prototype.getAuthor = function() { var $ = this._(key); return $.author_first + " " + $.author_last; }; return Book; })(); var bookA = new Book("Chris", "West"), bookB = new Book("Douglas", "Crockford"); alert(bookA.getAuthor()); alert(bookB.getAuthor()); </code></pre> <p>That is the same way that I implemented private members in jPaq.</p>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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