1 / 16

Object Oriented JavaScript

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.

melora
Download Presentation

Object Oriented JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented JavaScript

  2. 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

  3. 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); }; }

  4. 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

  5. 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

  6. 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__

  7. 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

  8. 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;

  9. 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); };

  10. 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

  11. 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);

  12. 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

  13. 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

  14. 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

  15. 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();

  16. 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();

More Related