-
Object Constructor and prototyping
- <!--
- //define class
- // Here the function "cat()" is an object constructor,
- // and its properties and methods are declared inside it by prefixing them
- // with the keyword "this." Objects defined using
- // an object constructor are then instantiated using the new keyword.
- // Notice how we're able to easily define multiple instances of cat, each with its own name- that's the flexibility object constructor brings to custom objects. Constructors create the blueprints for objects, not the object itself.
- function Cat(name){
- this.name=name;
- this.say=function(){
- alert("I am " + this.name);
- }
- }
- //instaniate an object
- cat1=new Cat("Newegg");
- cat1.say();
- cat2=new Cat("NEG");
- cat2.say();
- //Adding methods to our object using prototype
- //Lets extend our original cat() object above with an additional method to change the cat's name, using prototype
- Cat.prototype.changeName =function(newName){
- this.name=newName;
- }
- newCat=new Cat("name1");
- newCat.changeName("newName");
- newCat.say();
- //Using prototype on prebuilt JavaScript objects
- //IE5 doesn't support the shift() and unshift() methods of Array that NS4+ does, so lets prototype them in!
- if(!Array.prototype.shift){ //if the method does not exist
- Array.prototype.shift=function(){
- firstElement=this[0];
- this.reverse();
- this.length=Math.max(this.length-1,0);
- this.reverse();
- return firstElement;
- }
- }
- //-->
- </script>