1 / 9

Introduction to JavaScript Functions, Methods, and Prototypes in CS 142

This document covers fundamental JavaScript concepts, including functions, methods, prototypes, and object-oriented programming principles. It starts with simple examples like calculating sums and factorials, then progresses to object creation, method definitions, and property handling. Additionally, it discusses the implementation of constructors and how to embed external JavaScript code in HTML pages. Through these examples, learners can grasp how to manipulate objects and handle events effectively in JavaScript.

sirvat
Download Presentation

Introduction to JavaScript Functions, Methods, and Prototypes in CS 142

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. Simple Javascript Example sum = 0; for (i = 1; i < 10; i++) { sum += i*i; } CS 142 Lecture Notes: Javascript

  2. Factorial in Javascript functionfac(x) { if (x <= 1) { return 1; } return x*fac(x-1); } CS 142 Lecture Notes: Javascript

  3. Method Example o = new Object(); o.count = 0; o.increment = function(inc) { if (inc == undefined) { inc = 1; } this.count += inc; returnthis.count; } CS 142 Lecture Notes: Javascript

  4. Functions Can Have Properties function plus1(value) { if (plus1.invocations == undefined) { plus1.invocations = 0; } plus1.invocations++; return value+1; } CS 142 Lecture Notes: Javascript

  5. Constructor function Rectangle(width, height) { this.width = width; this.height = height; } r = new Rectangle(26, 14); CS 142 Lecture Notes: Javascript

  6. Methods (the wrong way) function Rectangle(width, height) { this.width = width; this.height = height; this.area= function() { returnthis.width*this.height; } } r = new Rectangle(26, 14); a = r.area(); CS 142 Lecture Notes: Javascript

  7. Prototypes function Rectangle(width, height) { this.width = width; this.height = height; } Rectangle.prototype.area = function() { returnthis.width*this.height; } r = new Rectangle(26, 14); a = r.area(); CS 142 Lecture Notes: Javascript

  8. Embedding Javascript External Javascript File <body> ... <script type="text/javascript" src="myCode.js" /> <script type="text/javascript"> //<![CDATA[ alert("Page is loading"); //]]> </script> <p onclick="alert(Hello, world!');"> Click here.</p> ... </body> Inline Code Event Handler CS 142 Lecture Notes: Javascript

  9. CS 142 Lecture Notes: Cookies

More Related