1.基本寫法
function Student(name,age,sex){ this.name=name; this.age=age; this.sex=sex; } //簡單的寫法 Student.prototype={ constructor:Student, height:"188px", width:"55kg", study:function(){ console.log("學習好凱西"); }, eat:function(){ console.log("我要吃好吃的"); }, } var stu=new Student("段飛",20,"女"); stu.eat(); stu.study(); console.log(Student); console.log(stu);
2.對象之間的方法的調用
//原型中的方法,是可以相互訪問的 function Animal(name,age) { this.name=name; this.age=age; } //原型中添加方法 Animal.prototype.eat=function () { console.log("動物吃東西"); this.play(); }; Animal.prototype.play=function () { console.log("玩球"); this.sleep(); }; Animal.prototype.sleep=function () { console.log("睡覺了"); }; var dog=new Animal("小蘇",20); dog.eat();
3.為內置對象添加原型方法
//為內置對象添加原型的方法,改變原有的方法 //倒敘輸出 String.prototype.myReverse=function(){ for(var i=this.length-1;i>=0;i--){ console.log(this[i]); } } var str="habcgacd"; str.myReverse(); //為Array內置對象的原型對象中添加方法 //為Array內置對象的原型對象中添加方法 Array.prototype.mySort=function () { for(var i=0;i<this.length-1;i++){ for(var j=0;j<this.length-1-i;j++){ if(this[j]<this[j+1]){ var temp=this[j]; this[j]=this[j+1]; this[j+1]=temp; }//end if }// end for }//end for }; var arr=[100,3,56,78,23,10]; arr.mySort(); console.log(arr); //為String添加一個sayHi的方法 String.prototype.sayHi=function(){ console.log("我又變帥了"); }; var str2="小楊"; str2.sayHi();