160 likes | 313 Views
Object Oriented JavaScript. JavaScript. Really only 4 types in JavaScript n umber, string, boolean Object (includes arrays) Remember that an object is really just a bunch of key-value pairs Ways to create an object Object literal Create a new blank object Write a constructor function.
E N D
JavaScript • Really only 4 types in JavaScript • number, string, boolean • Object (includes arrays) • Remember that an object is really just a bunch of key-value pairs • Ways to create an object • Object literal • Create a new blank object • Write a constructor function
Constructor functions • Normal JavaScript function • Called with new like Java • Generally sets some properties and methods using “this” • By convention, constructors start with uppercase letters • Called with new // Constructs and returns a new Point object. function Point(xValue, yValue) { this.x = xValue; this.y = yValue; this.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }; }
Prototypes • every object contains a reference to its prototype • default: Object.prototype; strings → String.prototype; etc. • a prototype can have a prototype, and so on • an object "inherits" all methods/data from its prototype(s) • doesn't have to make a copy of them; saves memory • prototypes allow JavaScript to mimic classes, inheritance
Prototypes • Every function/object stores a prototype object property in it • When we define the Point function (constructor) a Point.prototype is created • Every object created will use the function prototype object as its prototype • When new is called • A new object is created this • Attaches the function prototype to the object • Returns the new object
The Prototype Chain Object.prototype Point.prototype • When you ask for a property or method, JavaScript • sees if the object itself contains the property • recursively checks the objects prototype • continues up the prototype chain until the end and returns undefined if it cannot find it. x: 3 y: -4 __proto__ distanceToOrigin toString __proto__ __proto__
Using the Prototype for Methods // adding a method to the prototype function.prototype.name = function(params) { statements; }; Point.prototype.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }; • Adding a property/method to a prototype will make it available to all objects that use that prototype • Any prototype can be modified • Including built-in types
Inheritance using the Prototype function SuperClassName(parameters) { ... } function SubClassName(parameters) { ... } //Connect the prototype chain SubClassName.prototype = new SuperClassName(parameters); // Reset the constructor SubClassName.prototype.constructor = SubClassName • To make a subclass, set its prototype to an object of the superclass • Question: Why not this way? • SubClassName.prototype = SuperClassName.prototype;
Inheritance // Constructor for Point3D "subclass" function Point3D(x, y, z) { this.x = x; this.y = y; this.z = z; } // set it to be a "subclass" of Point Point3D.prototype = new Point(0, 0); // override distanceFromOrigin method to be 3D Point3D.prototype.distanceFromOrigin = function() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); };
Inheritance • There is no equivalent of the super keyword • no easy way to call the superclass's constructor • no built-in way to call an overridden superclass method • have to write it manually, e.g.var d = Point.prototype. distanceFromOrigin.apply(this); Or var d = Point.prototype. distanceFromOrigin.call(this); • Apply requires an array for function args • Call requires that function args are explicitly named
function A() // Define super classfunction A() // Define super class { this.x = 1; } A.prototype.DoIt = function() // Define Method { this.x += 1; } B.prototype = new A; // Define sub-class B.prototype.constructor = B; function B() { A.call(this); // Call super-class constructor (if desired) this.y = 2; } B.prototype.DoIt = function() // Define Method { A.prototype.DoIt.call(this); // Call super-class method (if desired) this.y += 1; } b = new B; document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>'); b.DoIt(); document.write(b.x + ', ' + b.y);
Private Members function A() { var x = 7; this.GetX = function() { return x;} this.SetX = function(xT) { x = xT; } } obj = new A; obj2 = new A; document.write(obj.GetX() + ' ' + obj2.GetX()); obj.SetX(14); document.write(' ' + obj.GetX() + ' ' + obj2.GetX()); • Create private members using local variables and methods • Closure allows access to the local variables
Namespaces • In JavaScript, there are only two scopes • Local and global • Problem: • In a large program, the namespace gets full • Using libraries complicates this more • Solution • The JavaScript Module Pattern
The JavaScript Module Pattern • Using global variables and self-executing functions, create the equivalent of a module • Note: self-executing functions • Typically a function is just declared until called • Javascript allows us to declare the function and have it called immediately (function() { alert(“Hello World”); })(); (function() { alert(“Hello World”); }()); OR
The JavaScript Module Pattern • Global variable • cs340.module • Everything else is private inside the module • Protected namespace • Returned object will run the constructor var cs340.module = (function () { // private variables and functions varfoo = 'bar'; // constructor varmodule = function () { }; // prototype module.prototype = { constructor: module, something: function () { } }; // return the module returnmodule; })(); varmy_module = newcs340.module();
JavaScript Module Namespace catan.models.ClientModel = (function clientModelNameSpace(){ varClientModel = (function ClientModelClass(){ varfullmodel = {}; function ClientModel(localConfig){ $("#debug").append("<br>In ClientModel Constructor"); } ClientModel.prototype.initFromServer = function(success){ … } ClientModel.prototype.getClientPlayerName = function(){ // TODO: Return the local player's correct name return "Sam"; } ClientModel.prototype.getClientPlayerColor = function(){ // TODO: Return the local player's correct color return "orange"; } return ClientModel; }()); return ClientModel; }()); varclientModel = new catan.models.ClientModel();