Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.23 KB | None | 0 0
  1. # Javascript Object Constructors
  2.  
  3. ---
  4.  
  5. ## Learning Objectives
  6. *After this lesson, students will be able to:*
  7. - Use constructor functions to create objects
  8. - Explain how `new` relates to constructor functions
  9. - Describe the need for constructor functions in OOP
  10. - Explain how `this` is used in constructor functions
  11. - Explain the difference between the returned values of regular functions and constructor functions
  12.  
  13. ---
  14.  
  15. ## Intro
  16.  
  17. - Constructor functions are useful in OOP (Object Oriented Programming) because they allow us to create multiple objects with specific properties and methods which we define.
  18. - Just like all arrays can access a set of methods defined in JavaScript, objects built using constructor functions we write can all access the methods which we define for that constructor.
  19. - We've already talked about how to make objects. Let's review a couple of ways to make them before we get to constructors.
  20.  
  21. ---
  22.  
  23. Creating objects using object literals:
  24.  
  25. ```js
  26. var freddie = {
  27. name: 'Freddie',
  28. hairColor: 'black'
  29. }
  30.  
  31. var mercury = {
  32. name: 'Mercury',
  33. hairColor: 'orange'
  34. }
  35.  
  36. var delilah = {
  37. name: 'Delilah',
  38. hairColor: 'grey'
  39. }
  40. ```
  41.  
  42. ---
  43.  
  44. Creating objects using functions that return an object:
  45.  
  46. ```js
  47. function cat(name, hairColor) {
  48. return {
  49. name: name,
  50. hairColor: hairColor
  51. }
  52. }
  53.  
  54. var freddie = cat('Freddie','black')
  55.  
  56. /*
  57. {
  58. name: 'Freddie',
  59. hairColor: 'black'
  60. }
  61. */
  62.  
  63. var mercury = cat('Mercury','orange')
  64.  
  65. /*
  66. {
  67. name: 'Mercury',
  68. hairColor: 'orange'
  69. }
  70. */
  71.  
  72. var delilah = cat('Delilah','grey')
  73.  
  74. /*
  75. {
  76. name: 'Delilah',
  77. hairColor: 'grey'
  78. }
  79. */
  80. ```
  81.  
  82. ---
  83.  
  84. ## Object Constructors
  85.  
  86. - Sometimes you will want several objects to represent similar things.
  87. - Object constructors can use a function as a template for creating objects.
  88.  
  89. ---
  90.  
  91. ### Think - Pair - Share
  92. Why might OOP be helpful in your first project?
  93.  
  94. ---
  95.  
  96. ### The `new` Keyword
  97.  
  98. - The `new` keyword and the object constructor create a blank object. You can then add properties and methods to the object.
  99. - Create an object using Object literal or Object constructor:
  100.  
  101. ```js
  102. var obj = {}
  103.  
  104. // or
  105.  
  106. var obj = new Object()
  107.  
  108. // both are the same!
  109. ```
  110. ---
  111.  
  112. - Just like with the JavaScript constructor `Object`, we can use the `new` keyword to create instances of our own constructor function.
  113.  
  114. ```js
  115. function Cat() {
  116.  
  117. }
  118.  
  119. var delilah = new Cat()
  120. ```
  121.  
  122. ---
  123.  
  124. ### The `this` Keyword
  125.  
  126. - The `this` keyword is used instead of the object name to indicate that the property or method belongs to the object that `this` function creates.
  127.  
  128. ```js
  129. function cat(name, hairColor) {
  130. var model = {}
  131.  
  132. model.name = name
  133. model.hairColor = hairColor
  134.  
  135. return model
  136. }
  137.  
  138. var mercury = cat('Mercury','orange')
  139. ```
  140. ---
  141.  
  142. - Use the `this` keyword in a *Constructor* function:
  143.  
  144. ```js
  145. function Cat(name, hairColor) {
  146. this.name = name
  147. this.hairColor = hairColor
  148. }
  149.  
  150. var freddie = new Cat('Freddie','black')
  151. ```
  152.  
  153. ---
  154.  
  155. #### Independent Work
  156.  
  157. - Create a constructor function for a car. It should have the following properties: make, model, and year.
  158.  
  159. <!--
  160. ```js
  161. function Car(make, model, year){
  162. this.make = make
  163. this.model = model
  164. this.year = year
  165. }
  166. ```
  167. -->
  168. ---
  169. * Use the `Car` constructor function to create two cars.
  170.  
  171. <!--
  172. ```js
  173. var elantra = new Car('Hyundai', 'Elantra', 2017)
  174. var a4 = new Car('Audi', 'A4', 2002)
  175. ```
  176. -->
  177.  
  178. ---
  179.  
  180. ### Object Inheritance
  181.  
  182. - Inheritance is when an object is based on another object, using the same implementation to maintain the same behavior.
  183. - Prototypes in Javascript can be used to add methods to all objects created by a specific constructor function, or to specify another constructor function from which this one inherits methods.
  184.  
  185. ---
  186.  
  187. #### Prototype
  188.  
  189. - What is a prototype?
  190.  
  191. ```javascript
  192. // A first, typical or preliminary model of something, especially a machine, from which other forms are developed or copied
  193. ```
  194.  
  195. - You have already been using inheritance! `String.toUpperCase()`, `Array.splice()`, etc.
  196. - Those methods are inherited from the String and Array constructors built into the core of JavaScript, and they are available on all instances of strings and arrays which you create.
  197.  
  198. ---
  199.  
  200. #### You can use `prototype` to add methods onto all of the objects that are created using a constructor function.
  201.  
  202. ```js
  203. var Machine = function(name, purpose) {
  204. this.name = name
  205. this.purpose = purpose
  206. }
  207.  
  208. Machine.prototype.purchase = function() {
  209. return 'You purchased a(n) ' + this.name + '.'
  210. }
  211.  
  212. var computer = new Machine('MacBook Pro', 'code and internet and stuff')
  213. var tablet = new Machine('iPad', 'internet and games and stuff')
  214.  
  215. computer.purchase() => 'You purchased a(n) MacBook Pro.'
  216. tablet.purchase() => 'You purchased a(n) iPad.'
  217. ```
  218.  
  219. ---
  220.  
  221. #### You can also use `prototype` to make a new constructor which inherits methods from another constructor.
  222.  
  223. ```js
  224. Phone.prototype = new Machine()
  225. Phone.prototype.constructor = Phone
  226. function Phone(brand, name) {
  227. this.brand = brand
  228. this.name = name
  229. this.purpose = 'to make calls, maybe?'
  230. }
  231.  
  232. var iPhone = new Phone('Apple', 'iPhone')
  233. var android = new Phone('Samsung', 'Galaxy S 7')
  234.  
  235. iPhone.purchase() => 'You purchased a(n) iPhone.'
  236. android.purchase() => 'You purchased a(n) Galaxy S 7.'
  237. ```
  238. ---
  239.  
  240. #### Notice that `purchase` was not specifically written for `Phone`, but it is available to `Phone` because `Phone` inherits it from `Machine`.
  241.  
  242. ---
  243.  
  244. ## Classes
  245.  
  246. ### Class declarations
  247.  
  248. - One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class.
  249.  
  250. ---
  251.  
  252. ```javascript
  253. class Polygon {
  254. constructor(height, width) {
  255. this.height = height;
  256. this.width = width;
  257. }
  258. }
  259. ```
  260.  
  261. ---
  262.  
  263. ### Class expressions
  264.  
  265. - A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body.
  266.  
  267. ---
  268.  
  269. ```javascript
  270. // unnamed
  271. var Polygon = class {
  272. constructor(height, width) {
  273. this.height = height;
  274. this.width = width;
  275. }
  276. };
  277.  
  278. // named
  279. var Polygon = class Polygon {
  280. constructor(height, width) {
  281. this.height = height;
  282. this.width = width;
  283. }
  284. };
  285. ```
  286. ---
  287.  
  288. ### Class Constructors
  289.  
  290. ```javascript
  291. class Polygon {
  292. constructor(height, width) {
  293. this.height = height;
  294. this.width = width;
  295. }
  296.  
  297. get area() {
  298. return this.calcArea();
  299. }
  300.  
  301. calcArea() {
  302. return this.height * this.width;
  303. }
  304. }
  305.  
  306. var square = new Polygon(10, 10);
  307.  
  308. console.log(square.area);
  309. ```
  310. ---
  311.  
  312. ### Static methods
  313.  
  314. - The static keyword defines a static method for a class.
  315. - Static methods are called without instantiating their class and are also not callable when the class is instantiated.
  316. - Static methods are often used to create utility functions for an application.
  317.  
  318. ---
  319.  
  320. ```javascript
  321. class Point {
  322. constructor(x, y) {
  323. this.x = x;
  324. this.y = y;
  325. }
  326.  
  327. static distance(a, b) {
  328. var dx = a.x - b.x;
  329. var dy = a.y - b.y;
  330.  
  331. return Math.sqrt(dx*dx + dy*dy);
  332. }
  333. }
  334. var p1 = new Point(5, 5);
  335. var p2 = new Point(10, 10);
  336. console.log(Point.distance(p1, p2));
  337. ```
  338. ---
  339.  
  340. ### Sub classing with extends
  341. - The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
  342. - We will see a similar pattern for inheritance in ruby and other languages
  343.  
  344. ---
  345.  
  346. ```javascript
  347. class Animal {
  348. constructor(name) {
  349. this.name = name;
  350. }
  351.  
  352. speak() {
  353. console.log(this.name + ' makes a noise.');
  354. }
  355. }
  356.  
  357. class Dog extends Animal {
  358. speak() {
  359. console.log(this.name + ' barks.');
  360. }
  361. }
  362.  
  363. var d = new Dog('Mitzie');
  364. d.speak();
  365. ```
  366. ---
  367.  
  368. #### super()
  369.  
  370. - If there is a constructor present in sub-class, it needs to first call super() before using "this".
  371. - One may also extend traditional function-based "classes":
  372.  
  373. ---
  374.  
  375. ```javascript
  376. class Cat {
  377. constructor(name) {
  378. this.name = name;
  379. }
  380.  
  381. speak() {
  382. console.log(this.name + ' makes a noise.');
  383. }
  384. }
  385.  
  386. class Lion extends Cat {
  387. speak() {
  388. super.speak();
  389. console.log(this.name + ' roars.');
  390. }
  391. }
  392. ```
  393. ---
  394.  
  395. #### Group Work
  396. - In 5 minutes, Using your `Car` constructor, do the following:
  397.  
  398. * Add a method to its prototype called `go`.
  399. + This function should accept a number.
  400. + If the number is at least 90, return 'Pedal to the metal!'
  401. + If the number is less than 90, return 'Speed up, granny!!'
  402.  
  403. ---
  404.  
  405. ```js
  406. Car.prototype.go = function(speed) {
  407. if(speed >= 90) {
  408. return "Pedal to the metal!"
  409. } else {
  410. return "Speed up, granny!"
  411. }
  412. }
  413. ```
  414.  
  415. ---
  416.  
  417. * Add another method to its prototype called `getDetails`.
  418. + This function should return the make, model and year of the car
  419.  
  420. <!--
  421. ```js
  422. Car.prototype.getDetails = function(){
  423. return 'This is a ' + this.year + ' ' + this.make + ' ' + this.model + '.'
  424. }
  425. ```
  426. -->
  427.  
  428. * Bonus: write a constructor for `Volkswagen` (or any make you choose) which inherits from `Car`. Make one Volkswagen using the constructor function. Check to make sure `go` and `getDetails` work on new instances of `Volkswagen`.
  429.  
  430. ---
  431.  
  432. <!--
  433. ```js
  434. Volkswagen.prototype = new Car()
  435. Volkswagen.prototype.constructor = Volkswagen
  436. function Volkswagen(model, year){
  437. this.make = 'Volkswagen'
  438. this.model = model
  439. this.year = year
  440. }
  441.  
  442. OR
  443.  
  444. function Volkswagen(model, year){
  445. Car.call(this, 'Volkswagen', model, year)
  446. }
  447.  
  448. var jetta = new Volkswagen('Jetta', 2007)
  449. ```
  450. -->
  451.  
  452. ---
  453.  
  454. ## Conclusion
  455.  
  456. - Explain the `new` key word.
  457. - How is `this` used in constructor functions?
  458. - Why are constructor functions useful in OOP?
  459. - What is the `prototype` property?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement