160 likes | 392 Views
Learn the fundamental concepts of JavaScript objects, including methods, properties, and constructors. Explore object creation and manipulation in JavaScript with examples and best practices.
E N D
JavaScript – Objects 2017, Fall Pusan National University Ki-Joune Li
JavaScript Objects – Basic Concepts • Object in JavaScript is a collection of variables with • Methods, • Properties (variables), • Definitions, • Constructor • In JavaScript, almost everything is object • Booleans can be objects (if defined with the new keyword) • Numbers can be objects (if defined with the new keyword) • Strings can be objects (if defined with the new keyword) • Dates, Maths, Regular Expression, Arrays, Functions, Objects are always objects • Except primitives – string, number, Boolean, null, undefined
JavaScript Objects – Basic Concepts • Object has • Method • Properties (Attributes) • Definition (e.g. macro definition) • Creating an object • Using a literal object • new Object() operator • User-defined Object constructor • Built-in JavaScript Constructor – Object(), String(), Number(), Boolean(), Array(), RegExp(), Function(), Date() • RegExp: Regular Expression Object – search pattern to search in a string • Syntax: /pattern/modifiersExample: var patt=/w3schools/i
JavaScript Objects – Basic Concepts var x = "John";var y = new String("John"); <script> var x = "John"; // x is a string var y = new String("John"); // y is an object document.getElementById("demo").innerHTML = (x==y); </script> • Primitive Types vs. Objects • Some primitive types can be created as objectsexample: • they can be compared : • But NOT Recommend to create primitive as an object – Why ? • Object-Object is not comparable – example
JavaScript Objects – Basic Concepts function person(firstName, lastName, age, eyeColor) {this.firstName = firstName; this.lastName = lastName;this.age = age;this.eyeColor = eyeColor;this.changeName = function (name) {this.lastName = name;};} • Adding New Methods • Adding methods to an object is done inside the constructor function: • Example
JavaScript Objects – String Object var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";var sln = txt.length; var str = "Please locate where 'locate' occurs!";var pos = str.indexOf("locate"); var str = "Please locate where 'locate' occurs!";var pos = str.search("locate"); var str = "Apple, Banana, Kiwi";var res = str.slice(7, 13) var str = "Apple, Banana, Kiwi";var res = str.substr(7, 6); str = "Please visit Microsoft!";var n = str.replace("Microsoft", "W3Schools"); str = "Please visit Microsoft and Microsoft!";var n = str.replace(/Microsoft/g, "W3Schools"); • Many methods can be applied • search can receive regular expression as well.
JavaScript Objects – String Object var text1 = "Hello World!"; // Stringvar text2 = text1.toUpperCase(); // text2 is text1 converted to upper var text1 = "Hello World!"; // Stringvar text2 = text1.toLowerCase(); // text2 is text1 converted to lower var text1 = "Hello";var text2 = "World";var text3 = text1.concat(" ", text2); var str = "HELLO WORLD";str.charAt(0); // returns H var str = "HELLO WORLD";str[0]; // returns H NOT a good idea, NOT Safe var txt = "a,b,c,d,e"; // Stringtxt.split(","); txt.split("|");
JavaScript Objects – Other Objects Number Object Math Object and Math Random
JavaScript – Array Objects sort.js function start() { var a=[10, 1, 9, 2, 30, 8, 7, 4, 5, 5]; outputArray("Data Items in the original order: ", a, document.getElementById("originalArray")); a.sort(CompareIntegers); outputArray("Data Items in the sorted order: ", a, document.getElementById("sortedArray")); } function outputArray(heading, theArray, output) { output.innerHTML=heading+theArray.join(" "); // insert blank between elements } function CompareIntegers(a, b) { return a-b;} window.addEventListener("load", start, false); Run start when this HTML document is loaded JavaScript supports array objects as other high level language.
JavaScript – Array Objects <!DOCTYPE html> <html> <body> <h2>JavaScript array</h2> <p>This is a sample function:</p> <script src="javaSample-array.js"></script> <!-- include js file --> <p id="originalArray"></p> <p id="sortedArray"></p> </body> </html>
JavaScript – Array Objects findMax.js function start() { var a=[10, 1, 9, 2, 30, 8, 7, 4, 5, 5]; var maxValue=findMax(a); outputArray("max value: ", maxValue, document.getElementById("result")); } function outputArray(heading, v, output) { output.innerHTML=heading+v; // insert blank between elements } function findMax(a) { var v=-100; for(var i in a) { if (a[i]> v) v=a[i];} // for(var i=0; i<a.length;i++) return v; } window.addEventListener("load", start, false); Find Max example.
JavaScript – Array Objects <!DOCTYPE html> <html> <body> <h2>JavaScript array</h2> <p>This is a sample function:</p> <script src="javaSample-array.js"></script> <p id=“result"></p> </body> </html>
JavaScript – Array Objects var a=[[10, 1], [9, 2], [30, 8]]; var a=[[10, 1], [9, 2], [30, 8, 7]]; var a=new Array(3); // allocate 2 rows a[0]=new Array(2); // allocate 2 columns to row 0 a[1]=new Array(2); // allocate 2 columns to row 1 a[2]=new Array(3); // allocate 3 columns to row 0 Multi-dimensional Array
JavaScript Objects – Prototypes function Person(first, last, age, eyecolor) {this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eyecolor;} var myFather = new Person("John", "Doe", 50, "blue");var myMother = new Person("Sally", "Rally", 48, "green"); myFather.nationality = "English"; myFather.name = function () {return this.firstName + " " + this.lastName; }; Once an object is created, we may add a new property or method.
JavaScript Objects – Prototypes <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } Person.prototype.nationality = "English"; var myFather = new Person("John", "Doe", 50, "blue"); document.getElementById("demo").innerHTML ="My father is " + myFather.nationality; Person.prototype.name = function() { return this.firstName + " " + this.lastName; }; document.getElementById("demo").innerHTML ="My father is " + myFather.name(); </script> </body></html> We can also add new properties or method using prototype