原型对象基本的写法和方法相互调用

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();
  

 

猜你喜欢

转载自www.cnblogs.com/liushisaonian/p/9425383.html
今日推荐