构造函数

js 构造函数

什么是构造函数:

  1. 在 JavaScript 中,用 new 关键字来调用的函数,称为构造函数。构造函数首字母一般大写
  2. 构造函数并没有显示返回任何东西。new 操作符会自动创建给定的类型并返回他们,当调用构造函数时,new会自动创建this对象,且类型就是构造函数类型。
  3. 也可以在构造函数中显示调用return.如果返回的值是一个对象,它会代替新创建的对象实例返回。如果返回的值是一个原始类型,它会被忽略,新创建的实例会被返回。
    构造函数一般以大写字母开头命名; 如:

fuction play(){…}

调用 :

任何函数,只要通过 new 操作符来调用,那它就可以作为构造函数 ;

//1函数2实例化3属4方5调用
			//模拟幻灯效果
			function play(){
		    //必须先自己构造一个函数,以后将这个行数名作对象名
					}
		   var p=new play();
		   //属性
				p.width=300;
				p.height=200;
				p.num=4;
				p.autotime=3;
		   //方法
				p.autoplay=function(){
		    alert("paly......")
					}
				p.test=function(){};
		   alert(p.width); //300
				p.autoplay();  //paly......

示例2:

//构造函数
			function play(){
				//获取
				var p = new Object();
				//属性
				p.width = 300;
				p.height = 200;
				p.num = 4;
				p.autotime = 3;
				//方法
				p.autoplay = function(){
					alert("play......");
					alert(this.num);
				}
				p.text = function (){}
					return p;
				}
				var obj = play();//obj=p
				alert(obj.width);//300
				obj.autoplay();//play
			

示例3:

//有this就得有对象
			function play(width,height,num){
				this.width=width;
				this.height=height;
				this.num=num;
				this.autoplay=function(){
					alert("########");
				}
				this.test=function(){
					
				}
				return this;
			}
			var p = new play(300,200,8); //重点
			alert(p.width);
			alert(p.height);
			p.autoplay();

示例4:

	//有this就得有对象
			function play(width,height,num){
				this.width=width;
				this.height=height;
				this.num=num;
				if(this.num<10){
					this.autoplay=function(){
						alert("参数的值为:" + this.num+ "  小于10");
					}
				}else{
					this.autoplay=function(){
						alert("参数的值为:" + this.num+ "  大于10");
					}
				}
				return this;
			}
			var p = new play(300,200,8); //重点
			//alert(p.width);
			//alert(p.height);
			p.autoplay();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值