zoukankan      html  css  js  c++  java
  • 原型对象基本的写法和方法相互调用

    1.基本写法

    function Student(name,age,sex){
    	
    	this.name=name;
    	this.age=age;
    	this.sex=sex;
    	
    }
    //简单的写法
    Student.prototype={
    	constructor:Student,
    	height:"188px",
    	"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();
      
    

     

  • 相关阅读:
    MySQL命令2
    MySQL命令1
    前端之HTML1
    linux命令之df dh
    python call java jar
    redis-py中的坑
    YARN应用程序的开发步骤
    Yarn的服务库和事件库使用方法
    SSH无密码验证
    在centos 6.5 在virtual box 上 安装增强版工具
  • 原文地址:https://www.cnblogs.com/liushisaonian/p/9425383.html
Copyright © 2011-2022 走看看