Lushprojects Blog
Projects in music, video, art, technology and learning
-
JavaScript Objects – some key examples
Posted on March 28th, 2017 No commentsSome of the JavaScript handling of objects is pretty wacky IMHO. Here is some code that illustrates some key points:
- Global, private and instance variables
- Privileged and private functions
- How “this” is assigned and how to work around that
See also: http://www.crockford.com/javascript/private.html
Some may point out that my application of OOP terminology to JavaScript isn’t correct. Strictly, what I am showing here are properties of the way JavaScript implements closures, but for people coming from an OOP perspective it’s helpful to be able to understand how to achieve some common OOish goals.
// This is a constructor Test function Test() { // Assign the private instance variable "self" to the value of this in the constructor. // More later on why we want to do this var self=this; // Assign a global variable g (probably not what you want to do in a real object!) g="global"; // Assign a private instance variable p var p = "private"; // Assign an instance variable i self.i = "instance"; // Create a private function pp (can't be accessed form outside the object) function pp () { console.log("pp"); } // Another way of assigning a private function var ppp = function () { console.log("ppp"); } // Create a 'privileged' function (public function that can access private info) this.p = function() { pp(); ppp(); console.log("p="+p); console.log("this.i="+this.i); console.log("self.i="+self.i); } } i="global i"; // assign i as a global o1 = new Test(); // o1.pp(); - would be an error - pp is private "o1.pp is not a function" // o1.ppp(); - would be an error - ppp is private. o1.p(); // Outputs 'pp', 'ppp', 'p=private', 'this.i=instance' and 'self.i=instance' console.log("Now with a call-back"); setTimeout(o1.p, 1000); // outputs 'pp', 'ppp', 'p=private', 'this.i=global i' and 'self.i=instance' // What's going on - // In the callback case the "this" is set to the current context which in this case is // the global document - hence getting the global "i" instead of the instance variable "i". // To get the instance variable i we want the value of "this" which was used during the // constructor which is stored in "self".