×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: userc865b
Added: Jun 30, 2017 2:19 PM
Modified: Jul 3, 2017 1:00 PM
Views: 2385
Tags: js
  1. <script>
  2. // ALTERNATIVE 1
  3.  
  4.     function Car (desc) {
  5.         this.desc = desc;
  6.         this.color = "red";
  7.     }
  8.  
  9.     Car.prototype = {
  10.         getInfo: function() {
  11.             return 'A ' + this.color + ' ' + this.desc + '.';
  12.         },
  13.         drive: function() {
  14.             //DO SOMETHING
  15.  
  16.             new Back("was los").drive();
  17.  
  18.  
  19.         },
  20.         stop: function() {
  21.             //DO SOMETHING
  22.         }
  23.     };
  24.  
  25.     function Back (desc) {
  26.         this.desc = desc;
  27.         this.color = "red";
  28.     }
  29.  
  30.     Back.prototype = {
  31.         getInfooooo: function() {
  32.             return 'A ' + this.color + ' ' + this.desc + '.';
  33.         },
  34.         drive: function() {
  35.             //DO SOMETHING
  36.             alert("hier Back");
  37.         },
  38.         stop: function() {
  39.             //DO SOMETHING
  40.         }
  41.     };
  42.  
  43. </script>
  44.  
  45. <input  onchange="new Car(null).drive();"/>
  46.  
  47. ////// ALTERNATIVE 2
  48.  
  49. //Constructor
  50. var Person = function (name, age){
  51.     //private properties
  52.     var priv = {};
  53.    
  54.     //Public properties
  55.     this.name = name;
  56.     this.age = age;
  57.    
  58.     //Public methods
  59.     this.sayHi = function(){
  60.         alert('hello');
  61.     }
  62. }
  63.  
  64. // A static method; this method only
  65. // exists on the class and doesn't exist
  66. // on child objects
  67. Person.sayName = function() {
  68.     alert("I am a Person object ;)");  
  69. };
  70.  
  71. // An instance method;
  72. // All Person objects will have this method
  73. Person.prototype.setName = function(nameIn) {
  74.     this.name = nameIn;  
  75. }
  76.  
  77. // Tests
  78. var per = new Person('John Doe', 22);
  79.  
  80. //Shows alert
  81. Person.sayName();
  82.  
  83. //TypeError: Object [object Object] has no method 'sayName'
  84. per.sayName()
  85.  
  86. //Show alert
  87. per.sayHi();
  88.  
  89. //John Doe
  90. per.name;
  91.  
  92. //22
  93. per.age;
  94.  
  95. per.setName('Jane Doe');
  96.  
  97. //Jane Doe
  98. per.name;