JavsScript OOP

Download JavsScript OOP

Post on 15-Jul-2015

153 views

Category:

Software

0 download

Embed Size (px)

TRANSCRIPT

<p>JAVASCRIPT OOPKim 2015.04.24Object-oriented programmingOOP envisions software as a collection of cooperating objects rather than a collection of functions or simply a list of commands (as is the traditional view). </p> <p>In OOP, each object can receive messages, process data, and send messages to other objects. </p> <p> Each object can be viewed as an independent little machine with a distinct role or responsibility.Object-oriented programmingOOP promotes greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering.</p> <p>Because OOP strongly emphasizes modularity, object-oriented code is simpler to develop and easier to understand later on.</p> <p>Object-oriented code promotes more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methodsTerminologyNamespaceA container which lets developers bundle all functionality under a unique, application-specific name.ClassDefines the object's characteristics. A class is a template definition of an object's properties and methods.ObjectAn instance of a class.PropertyAn object characteristic, such as color.MethodAn object capability, such as walk. It is a subroutine or function associated with a class.</p> <p>TerminologyConstructorA method called at the moment an object is instantiated. It usually has the same name as the class containing it.InheritanceA class can inherit characteristics from another class.EncapsulationA method of bundling the data and methods that use the data.AbstractionThe conjunction of an object's complex inheritance, methods, and properties must adequately reflect a reality model.PolymorphismPoly means "many" and morphism means "forms". Different classes might define the same method or property.Prototype-based programmingPrototype-based programming is an OOP model that doesn't use classes, but rather accomplishes behavior reuse (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)</p> <p>JavaScript object oriented programmingA namespace is a container which allows developers to bundle up functionality under a unique, application-specific name. </p> <p>In JavaScript a namespace is just another object containing methods, properties, and objects.</p> <p>// global namespacevar MYAPP = MYAPP || {};// sub namespaceMYAPP.event = {};</p> <p>JavaScript object oriented programming// Create container called MYAPP.commonMethod for common method and propertiesMYAPP.commonMethod = { regExForName: "", // define regex for name validation regExForPhone: "", // define regex for phone no validation validateName: function(name){ // Do something with name, you can access regExForName variable // using "this.regExForName" }, validatePhoneNo: function(phoneNo){ // do something with phone number }}</p> <p>// Object together with the method declarationsMYAPP.event = { addListener: function(el, type, fn) { // code stuff }, removeListener: function(el, type, fn) { // code stuff }, getEvent: function(e) { // code stuff } // Can add another method and properties}</p> <p>// Syntax for Using addListener method:MYAPP.event.addListener("yourel", "type", callback);</p> <p>Standard built-in objectsJavaScript has several objects included in its core, for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.</p> <p>console.log(Math.random());Standard objectsValue propertiesThese global properties return a simple value; they have no properties or methods.InfinityNaNundefinednull</p> <p>Function propertiesThese global functionsfunctions which are called globally rather than on an objectdirectly return their results to the caller.isFinite()isNaN()parseFloat()parseInt()decodeURI()encodeURI()Fundamental objectsObjectFunctionBooleanErrorRangeErrorTypeError</p> <p>Numbers and datesThese are the base objects representing numbers, dates, and mathematical calculations.NumberMathDate</p> <p>Text processingThese objects represent strings and support manipulating them.StringRegExp</p> <p>Custom objectsThe classvar Person = function () { console.log('instance created');};</p> <p>var person1 = new Person();var person2 = new Person();</p> <p>Custom objectsThe property (object attribute)Properties are variables contained in the class; every instance of the object has those properties. Properties are set in the constructor (function) of the class so that they are created on each instance.var Person = function (firstName) { this.firstName = firstName; console.log('Person instantiated');};</p> <p>var person1 = new Person('Alice');var person2 = new Person('Bob');</p> <p>// Show the firstName properties of the objectsconsole.log('person1 is ' + person1.firstName); // logs "person1 is Alice"console.log('person2 is ' + person2.firstName); // logs "person2 is Bob"</p> <p>Custom objectsThe methodsvar Person = function (firstName) { this.firstName = firstName;};</p> <p>Person.prototype.sayHello = function() { console.log("Hello, I'm " + this.firstName);};</p> <p>var person1 = new Person("Alice");var person2 = new Person("Bob");</p> <p>// call the Person sayHello method.person1.sayHello(); // logs "Hello, I'm Alice"person2.sayHello(); // logs "Hello, I'm Bob"</p> <p>Custom objectsvar Person = function (firstName) { this.firstName = firstName;};</p> <p>Person.prototype.sayHello = function() { console.log("Hello, I'm " + this.firstName);};</p> <p>var person1 = new Person("Alice");var person2 = new Person("Bob");var helloFunction = person1.sayHello;</p> <p>// logs "Hello, I'm Alice"person1.sayHello();</p> <p>// logs "Hello, I'm Bob"person2.sayHello();</p> <p>// logs "Hello, I'm undefined" (or fails// with a TypeError in strict mode)helloFunction(); </p> <p>// logs trueconsole.log(helloFunction === person1.sayHello);</p> <p>// logs trueconsole.log(helloFunction === Person.prototype.sayHello);</p> <p>// logs "Hello, I'm Alice"helloFunction.call(person1);</p> <p>Inheritancevar Person = function(firstName) { this.firstName = firstName;};Person.prototype.walk = function(){ console.log("I am walking!");};Person.prototype.sayHello = function(){ console.log("Hello, I'm " + this.firstName);};</p> <p>Inheritance// Define the Student constructorfunction Student(firstName, subject) { // Call the parent constructor, making sure (using Function#call) // that "this" is set correctly during the call Person.call(this, firstName);</p> <p> // Initialize our Student-specific properties this.subject = subject;};</p> <p>InheritanceStudent.prototype = Object.create(Person.prototype); // See note below</p> <p>// Set the "constructor" property to refer to StudentStudent.prototype.constructor = Student;</p> <p>// Replace the "sayHello" methodStudent.prototype.sayHello = function(){ console.log("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + ".");};</p> <p>// Add a "sayGoodBye" methodStudent.prototype.sayGoodBye = function(){ console.log("Goodbye!");};</p> <p>Inheritance// Example usage:var student1 = new Student("Janet", "Applied Physics");student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics."student1.walk(); // "I am walking!"student1.sayGoodBye(); // "Goodbye!"</p> <p>// Check that instanceof works correctlyconsole.log(student1 instanceof Person); // true console.log(student1 instanceof Student); // true</p>