Programming in HTML with JavaScript and CSS3.
Implementing inheritance and encapsulation in javascript
JavaScript doesn’t use classes, everything is an object; A custom object is made up of properties where some properties are native types and some properties are assigned to functions to implement methods.
Implementing inheritance in JavaScript
Every object has a prototype and every prototype is an object All objects inherit properties and methods from their prototypes (hence why it is the basis of inheritance).
Prototyping is also an easy way to add properties and methods to objects that have already been instantiated.
The following code gives an example of inheritance:
The following code gives an example of inheritance:
<body>
<input type="submit" onclick="inheritance()" value="INHERITANCE" /><br />
<!-- INHERITANCE -->
<script type="text/javascript">
var inheritance = function() {
function Mammal(name) {
this.name = name;
this.offspring = [];
}
Mammal.prototype.haveABaby = function () {
var newBaby = new Mammal("Baby " + this.name);
this.offspring.push(newBaby);
return newBaby;
}
Mammal.prototype.toString = function () {
return '[Mammal "' + this.name + '"]';
}
// Here's where the inheritance occurs
Cat.prototype = new Mammal();
// Otherwise instances of Cat would have a constructor of Mammal
Cat.prototype.constructor = Cat;
function Cat(name) {
this.name = name;
}
Cat.prototype.toString = function () {
return '[Cat "' + this.name + '"]';
}
var someAnimal = new Mammal('Mr. Biggles');
var myPet = new Cat('Felix');
// results in 'someAnimal is [Mammal "Mr. Biggles"]'
alert('someAnimal is ' + someAnimal);
alert('myPet is ' + myPet); // results in 'myPet is [Cat "Felix"]'
myPet.haveABaby(); // calls a method inherited from Mammal
alert(myPet.offspring.length); // shows that the cat has one baby now
alert(myPet.offspring[0]); // results in '[Mammal "Baby Felix"]'
}
</script>
</body>
Encapsulation in JavaSvript
Encapsulation in JavaScript is the same as it is in other OOP languages. Though private and public methods are not used in JavaScript to hide functionality, some methods we have discussed were made to help us with that issue.
In the following code example:
- The In Operator: Will tell you if a property exists in an object
- hasOwnProperty method: Will tell you if a specific property is unique to an object
- For/in loop: To access all the properties in an object
<body>
<input type="submit" onclick="encapsulation()" value="ENCAPSULATION" /><br />
<!-- ENCAPSULATION -->
<script type="text/javascript">
var encapsulation = function () {
var seafood = { small: "shrimp", big: "shark" };
alert("small" in seafood); // true
alert(seafood.hasOwnProperty("toString")); //false
for (var item in seafood) {
alert(item); //prints the small and big seafood
}
}
//toSTring was inherited by the Object prototype, it is not unique to the seafood object
//The for/in loop will print inherited objects
</script>
</body>
Ads Right