现在的位置: 首页 > 综合 > 正文

OOP in Javascript(2)

2013年04月16日 ⁄ 综合 ⁄ 共 1811字 ⁄ 字号 评论关闭
 

  • Object Constructor and prototyping
  1.     <!--
  2.         
  3. //define class
  4. //        Here the function "cat()" is an object constructor,
  5. //         and its properties and methods are declared inside it by prefixing them 
  6. //         with the keyword "this." Objects defined using 
  7. //         an object constructor are then instantiated using the new keyword. 
  8. //         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.
  9.         function Cat(name){
  10.             this.name=name;
  11.             this.say=function(){
  12.                 alert("I am " + this.name);
  13.             }
  14.         
  15.         }   
  16.         //instaniate an object
  17.         cat1=new Cat("Newegg");
  18.         cat1.say();
  19.         cat2=new Cat("NEG");
  20.         cat2.say();
  21.         
  22.         
  23.         //Adding methods to our object using prototype 
  24.         //Lets extend our original cat() object above with an additional method to change the cat's name, using prototype
  25.         Cat.prototype.changeName =function(newName){
  26.             this.name=newName;
  27.         }
  28.         
  29.         newCat=new  Cat("name1");
  30.         newCat.changeName("newName");
  31.         newCat.say();
  32.         
  33.         //Using prototype on prebuilt JavaScript objects 
  34.         //IE5 doesn't support the shift() and unshift() methods of Array that NS4+ does, so lets prototype them in!
  35.     
  36.         if(!Array.prototype.shift){ //if the method does not exist
  37.             Array.prototype.shift=function(){
  38.                 firstElement=this[0];
  39.                 this.reverse();
  40.                 this.length=Math.max(this.length-1,0);
  41.                 this.reverse();
  42.                 return firstElement;
  43.             }
  44.             
  45.         }
  46.         
  47.         
  48.     //-->
  49.     </script>

 

 

 

抱歉!评论已关闭.