js 构造函数
什么是构造函数:
- 在 JavaScript 中,用 new 关键字来调用的函数,称为构造函数。构造函数首字母一般大写
- 构造函数并没有显示返回任何东西。new 操作符会自动创建给定的类型并返回他们,当调用构造函数时,new会自动创建this对象,且类型就是构造函数类型。
- 也可以在构造函数中显示调用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();