CS 11: Javascript Track

CS 11: Javascript Track

CS 11: Javascript track Lecture 2: Basics and OOP Caltech CS 11 JS 1 To d ay Javascript basics § primitive types § compound types • objects • arrays § variable declarations § functions Caltech CS 11 JS 2 To d ay Object-oriented programming (OOP) in Javascript § Objects or classes? § Prototypes § The prototype chain § Object creation using Object.create() § Object creation using new • functions as constructors § The many faces of this Caltech CS 11 JS 3 To d ay The purpose of this lecture is to explain enough Javascript so that you can get through assignments 1 and 2 We assume that you know C or Java or both We will highlight aspects of Javascript that differ from C/Java We will then describe object-oriented programming (OOP) in Javascript Caltech CS 11 JS 4 Primitive types Here are the primitive types in Javascript: § null § undefined § boolean (true or false) § number (double-precision floating-point) • no integers! • use e.g. 100 | 0 if you want to make sure a number is an integer (ugh!) • vertical bar character (|) is "bitwise or" § string • uses ' ' or " " as delimiters (like Python) Caltech CS 11 JS 5 Compound types Here are the compound types in Javascript: § objects § arrays Arrays are actually a special kind of object, so really, the only compound type is "object" Functions (anonymous or not) are also a distinct type, and also a special kind of object Caltech CS 11 JS 6 Objects Objects are basically name/value mappings (hash tables with strings as keys) Object literals can be created using curly braces: { foo : 1, s : "I am a string" } Caltech CS 11 JS 7 Local variables Define local variables using the var keyword: var x = 0; If you leave out the var, it's not an error, but x will become a global variable! § So don't do it! § Ever! § I'm serious! NEVER do that! vars are scoped over the entire function they occur in, no matter where in the function they occur Caltech CS 11 JS 8 Objects You can access fields of an object using the dot syntax: var obj = { foo : 1, s : "I am a string" } ; obj.foo // 1 obj.s // "I am a string" You can mutate object fields the same way: obj.foo = "I am now a string"; obj.s = 42; Caltech CS 11 JS 9 Objects You can add fields to an object at any time: var obj = { foo : 1, s : "I am a string" } ; obj.frobnitz = 1001.3; You can access object fields using strings instead of bare words: obj.foo = 1001; obj["foo"] // 1001 obj["foo"] = 99.9; obj["this is an unusual field name"] = true; Caltech CS 11 JS 10 Equality comparison Compare two values for equality using the === operator Compare two values for inequality using the !== operator NOTE! There are also == and != operators, but DO NOT USE THEM! § They coerce types in weird ways! Caltech CS 11 JS 11 Functions Function syntax for named functions: function add(x, y) { return x + y; } Anonymous functions: function(x, y) { return x + y; } Caltech CS 11 JS 12 Methods Methods are just function values inside of objects: var myobj = {}; myobj.add = function(x, y) { return x + y; }; myobj.add(2, 3) // 5 Caltech CS 11 JS 13 Arrays Arrays are a kind of object Arrays have literal syntax: var myarr = [1, 2, 3, 4, 5]; Arrays use square brackets for accessing elements: myarr[0] = 42; myarr[3] // 4 Arrays have a length attribute: myarr.length // 5 Caltech CS 11 JS 14 WAT > typeof(1) 'number' > typeof('foo') 'string' > typeof({}) 'object' > typeof([1, 2, 3, 4, 5]) 'object' > typeof(function (x, y) { return x + y; }) 'function' Caltech CS 11 JS 15 Objects or classes? Objects are a fundamental data type in Javascript Objects are basically just key/value maps (like Python dictionaries) where the keys have to be strings Keys that are identifiers can be bare words: var myobj = { foo: 10, bar: 20 }; Otherwise, use quotes: var myobj = { foo: 10, "hello world" : 42 }; Caltech CS 11 JS 16 Objects or classes? Most object-oriented programming languages are class-based § They use classes as a template to build objects § Classes define the object constructor and the inheritance relationship However, there is nothing fundamental about classes Some OOP languages have experimented with classless object systems Caltech CS 11 JS 17 Objects or classes? One of the earliest object-oriented languages that didn't use classes was called Self § mainly a research language developed at Sun Microsystems Self was one of the principal inspirations for Javascript (along with Scheme) Javascript, like Self, does not use classes in its object-oriented system Caltech CS 11 JS 18 Objects or classes? Nevertheless, Javascript is profoundly object- oriented Almost all interesting code in Javascript makes heavy use of objects What is used in place of classes? Answer: Prototypes Caltech CS 11 JS 19 What classes provide Before we describe what prototypes are, let's see what classes provide in class-based OOP languages § A place where fields and methods are defined § A place where object constructors are defined § A place where inheritance relationships are specified Javascript needs all of these things, so there must be ways to do these without classes Caltech CS 11 JS 20 Objects and properties Javascript uses plain old objects as a repository for fields and methods § which are called "properties" in Javascript Objects can be created using object literals: var myobj = { foo: 1, bar: 2 }; New properties can be added at any time: myobj.baz = 42; Methods are just properties which are functions: myobj.add = function(x, y) { return x + y; }; Caltech CS 11 JS 21 this, part 1 Actually, methods are slightly more than just functions When a method is called on an object, the object is bound to a variable called this var myobj = { count: 0; } myobj.inc = function() { this.count++; } As we will see, this has a bunch of other rules associated with it Caltech CS 11 JS 22 Properties Properties can be created on the fly, deleted (using the delete operator), mutated, or looked up Creating properties on the fly, deleting properties, or mutating properties only affects the named object itself (as you'd expect) Looking up properties is more complex § If the property exists in the object, just return that value § Otherwise, look it up in the object's prototype Caltech CS 11 JS 23 Prototypes Prototypes are Javascript's equivalent to inheritance in other OO languages Prototypes are used to handle the case where a requested property doesn't exist in an object In that case, the property is looked up in the object's prototype If that fails too, the property is looked up in the prototype's prototype, etc. until § the property is found, in which case it's returned § there are no more prototypes, in which case undefined is returned Caltech CS 11 JS 24 Prototypes The cool part: any object can act as a prototype! There is no class/object distinction in Javascript In traditional languages, classes serve as prototypes and objects as units of computation In Javascript, the same objects can fulfill both roles This makes the system extremely flexible Caltech CS 11 JS 25 Prototypes OK, so how do we specify what the prototype of a particular object is? This leads to our next topic… Caltech CS 11 JS 26 Constructors So far: § We've got a way to put fields and methods (properties) into objects § We know that property lookup failures cause the system to continue looking up the property in an object's prototype We still need § a way to create objects based on some sort of a template • because most of the time, need to make more than one object of each kind § a way to set the prototype for created objects Javascript has two main ways to do this Caltech CS 11 JS 27 Constructors (1st way) To create an object, you can call the Object.create method with one argument, which is the prototype of the new object var myproto = { foo: 1001, bar: 42 }; var myobj = Object.create(myproto); myobj.foo // 1001 myobj.foo = 10; // shadow prototype property myobj.foo // 10 myproto.foo // 1001 delete myobj.foo; // unshadow property 'foo' myobj.foo // 1001 Caltech CS 11 JS 28 __proto__ Note: some JS implementations (Firefox, Chrome browsers, Node.js), use a special field called __proto__ to hold the prototype of an object Other Javascript implementations hide the field containing the prototype, so it isn't directly accessible Don't assume this field will exist in any particular JS implementation § and if it does exist, leave it alone! Caltech CS 11 JS 29 Accessing the prototype If you must interact directly with an object's prototype, there are standard functions to allow you to do this: Object.getPrototypeOf(someObject) Object.setPrototypeOf(someObject, someProto) We very strongly advise against using setPrototypeOf! § slow, and can radically mess up object hierarchies Normally, you don't need either of these functions Caltech CS 11 JS 30 Constructors (2nd way) Another way to create objects is to use a constructor function In true Javascript fashion, any function can be a constructor function! A function is treated as a constructor of an object if it is called with the new keyword The object being created inside the constructor is accessed using the this keyword (second use of this) Caltech CS 11 JS 31 Constructors (2nd way) Example of a function used as a constructor: function Point(x, y) { // this is the object being constructed this.x = x; this.y = y; } var myPoint = new Point(10, 20); Constructor function names are capitalized by convention Caltech CS 11 JS 32 Constructors (2nd way) Constructor function names (like Point) are capitalized by convention new assigns a new (empty)

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    43 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us