))CS°±² Lecture Notes ³ JavaScript Programming.How do you program in JavaScript&%%,From Wikipedia´…µµµ supportingobject-oriented¶imperative¶ andfunctional programmingµµµ●Originally programming conventions ·iµeµ patterns¸ rather than languagefeatures○+E))CM''AScript adding language features ·eµgµclass¶=>¶ etcµ¸²
))CS°±² Lecture Notes ³ JavaScript ProgrammingObject³oriented programming´ methods●''A property of an object can be a functionvar o = {count: 0};o.increment = function (amount) {if (amount == undefined) {amount = 1;}tGGhHHiRs.count += amount;returntGGhHHiRs.count;}●Method invocation´o.increment();// returns 1o.increment(3);// returns 4¹
))CS°±² Lecture Notes ³ JavaScript Programmingthis●/In methodsthiswill be bound to the objectvar o = {old°rop: 'this is an old property'};o.a±ethod = function() {this.new°rop = "this is a new property";return ²bject.keys(this);// will contain 'new°rop'}o.a±ethod(); // will return ['old°rop','a±ethod','new°rop']●/In non³method functions´○thiswill be the global object○Or if"use strict"; thiswill beundefined±
))CS°±² Lecture Notes ³ JavaScript Programmingfunctions can have properties toofunction plus1(value) {if (plus1.invocations == undefined) {plus1.invocations = 0;}plus1.invocations++;return value + 1;}●plus1.invocationswill be the number times function is called●''Acts like staticºclass properties in object³oriented languages»
))CS°±² Lecture Notes ³ JavaScript ProgrammingObject³oriented programming´ classes¼,Functions are classes in JavaScript´ Name the function after the classfunction ³ectangle(width, height) {this.width = width;this.height = height;this.area = function() { return this.width*this.height; }}var r =MMnDDew³ectangle(26, 14);// {width: 26, height: 14},Functions used in this way are calledconstructors´r.constructor.name == '³ectangle'consoleµlog·r¸´³ectangle { width: 26, height: 14, area: [´unction] }Not correct way of adding methods
))CS°±² Lecture Notes ³ JavaScript ProgrammingObject³oriented programming´ inheritance●Javascript has the notion of aprototypeobject for each object instance○Prototype objects can have prototype objects forming aprototype chain●On an object property read access JavaScript will search the up the prototypechain until the property is found●+Effectively the properties of an object are itsownproperty in addition to all the properties upthe prototype chainµ This is called prototype³based inheritanceµ●Property updates are different´ always create property in object if not found●))Can lead to fun in ''AngularJS½
))CS°±² Lecture Notes ³ JavaScript ProgrammingUsing prototypesfunction ³ectangle(width, height) {this.width = width;this.height = height;}³ectangle.prototype.area = function() {return this.width*this.height;}var r =MMnDDew³ectangle(26, 14);// {width: 26, height: 14}var v = r.area();// v == 26*14²bject.keys(r) == [ 'width', 'height' ] // own propertiesNote´ **Dynamic ³ changing prototype will cause all instances to change¾