Guest User

Untitled

a guest
Sep 14th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. Javascript object inheritance
  2. var person = {
  3. 'first-name': 'FirstName',
  4. 'last-name': 'LastName',
  5. 'gender': 'Male'
  6. };
  7.  
  8. var anotherPerson = new Object(person);
  9. anotherPerson.desig = 'Designation';
  10.  
  11. console.log('Another person designation: ' + anotherPerson['desig'] + ', person designation: ' + person['desig']);
  12.  
  13. person.place = 'XYZ';
  14. console.log(person['place'] + ', ' + anotherPerson['place']); // Expected: XYZ, undefined. Result: XYZ, XYZ.
  15.  
  16. person = undefined;
  17. console.log(anotherPerson['place']) //Expected: error, Result: XYZ. ??!?!?
  18. console.log(person['place']) // Expected: error, Result: error.
  19.  
  20. var Person = function () {
  21. this["first-name"] = 'FirstName',
  22. this["last-name"] = 'LastName',
  23. this["gender"] = 'Male'
  24. };
  25.  
  26. var person = new Person();
  27. var anotherPerson = new Person();
  28.  
  29. var Person = function () {
  30. this["first-name"] = 'FirstName',
  31. this["last-name"] = 'LastName',
  32. this["gender"] = 'Male'
  33. };
  34.  
  35. var AnotherPerson = function () {
  36. this.desig = "Designation";
  37. }
  38. AnotherPerson.prototype = new Person(); // inherit from Person
  39. AnotherPerson.prototype.constructor = AnotherPerson; // reset constructor
  40.  
  41. var person = new Person();
  42. var anotherPerson = new AnotherPerson();
  43.  
  44. console.log(person.desig); // undefined
  45. console.log(anotherPerson.desig); // Designation
  46.  
  47. var person = {
  48. 'first-name': 'FirstName',
  49. 'last-name': 'LastName',
  50. 'gender': 'Male'
  51. };
  52. if (typeof Object.create !== 'function')
  53. {
  54. Object.create=function(o)
  55. {
  56. function F(){}
  57. F.prototype=o;
  58. return new F();
  59. }
  60. }
  61. var newPerson=Object.create(person);
  62. newPerson.age=25;
  63. newPerson.gender="Female";
  64.  
  65. console.log(person.gender); // Male
  66. console.log(newPerson.gender); // Female
  67.  
  68. console.log(person.age); // undefined
  69. console.log(newPerson.age); // 25
  70.  
  71. var anotherPerson = new Object();
  72. for(i in person) anotherPerson[i]=person[i];
  73.  
  74. var anotherPerson = new Object(person);
Add Comment
Please, Sign In to add comment