在学习构造函数之前我们需要知道我们学习构造函数需要学习什么:1.什么是构造函数2.构造函数用来做什么3.构造函数的执行过程4.构造函数的返回值1.所以首先我们需要知道什么是构造函数:
1.所以首先我们需要知道什么是构造函数:
在我看来,构造函数具有两个特点可以判断是否为构造函数:1.当函数名为首字母大写时,这个是一个可以大概判断构造函数与普通函数的一个特点,但是不是绝对正确,因为普通函数也可以是大写字母开头2.当我们需要调用构造函数时我们需要new <构造函数>,也就是产生一个实例化对象。
function Student(name,age,sex,height){

this.name=name;

this.age=age;

this.sex=sex;

this.height=height;

}

//调用构造函数,也就是实例化一个对象。

var p=new Student('luke',23,'nan',180)

console.log(p);
function Student(name,age,sex,height){

this.name=name;

this.age=age;

this.sex=sex;

this.height=height;

}

//调用构造函数,也就是实例化一个对象。

var p=new Student('luke',23,'nan',180)

console.log(p);控制台输出:可以看出输出的是一个对象2.构造函数是用来做什么的:
2.构造函数是用来做什么的:1.当我们平时创建对象时可能会用如下创建对象的方式来创建,上代码:
//用创建对象方式来创建

var stu1={name:'zs',age:20,sex:"male",height:186};

var stu2={name:'ls',age:21,sex:"male",height:180}

var stu3={name:'ww',age:22,sex:"female",height:156}

var stu4={name:'jx',age:23,sex:"female",height:165}

var stu5={name:'xf',age:24,sex:"male",height:180}
//用创建对象方式来创建

var stu1={name:'zs',age:20,sex:"male",height:186};

var stu2={name:'ls',age:21,sex:"male",height:180}

var stu3={name:'ww',age:22,sex:"female",height:156}

var stu4={name:'jx',age:23,sex:"female",height:165}

var stu5={name:'xf',age:24,sex:"male",height:180}2.当我们用构造函数来创建这个对象时:
//用构造函数来创建对象

function Student(name,age,sex,height){

this.name=name;

this.age=age;

this.sex=sex;

this.height=height;

}

var stu1=new Student('zs',20,"male",186);

var stu2=new Student('ls',21,"male",180);

var stu3=new Student('ww',22,"female",156);

var stu4=new Student('jx',23,"female",165);

var stu5=new Student('xf',24,"male",180);
//用构造函数来创建对象

function Student(name,age,sex,height){

this.name=name;

this.age=age;

this.sex=sex;

this.height=height;

}

var stu1=new Student('zs',20,"male",186);

var stu2=new Student('ls',21,"male",180);

var stu3=new Student('ww',22,"female",156);

var stu4=new Student('jx',23,"female",165);

var stu5=new Student('xf',24,"male",180);这样看起来是不是要简洁的多呢,这里因为只有五个人,要是五六十个就会看出明显效果3.构造函数的执行过程
3.构造函数的执行过程
在前面我们知道了构造函数是什么,和其作用,也通过代码来看出了构造函数的作用。那我现在我们需要知道构造函数的执行过程,因为学习一个东西我们需要学习其原理,而不是其表面所以接下来我就来讲一讲构造函数的执行过程:在之前我们都知道,要调用构造函数我们需要在其前面加一个new关键字,所以主要就是new在其作用,在执行new关键字后,很明显,他跟以往的函数调用就不同了,他会依次执行以下步骤:1.new过后会产生一个空对象,作为一个返回的对象实例2.将空对象的原型指向了构造函数的prototype属性3.将空对象的值赋值给构造函数里面的this值4.开始执行构造函数里的代码4.构造函数的返回值
4.构造函数的返回值
知道了其执行过程,显而易见,new关键字创建的实例对象为构造函数的返回值。其实这是不对的,哈哈。返回值需要分情况来定:1.当函数中没有return来返回值的时候,会返回this,也就是实例化对象。就像在说2.构造函数有什么作用时说的一样2.当函数中return中返回一个复杂类型数据的时候,构造函数会返回这个复杂类型数据,上代码:
function Student(name,age,sex,height){

this.name=name;

this.age=age;

this.sex=sex;

this.height=height;

return {name:'fanhui',weight:60}

}

var Stu1=new Student('zs',20,"male",186);

console.log(Stu1);
function Student(name,age,sex,height){

this.name=name;

this.age=age;

this.sex=sex;

this.height=height;

return {name:'fanhui',weight:60}

}

var Stu1=new Student('zs',20,"male",186);

console.log(Stu1);以上就是本文的全部内容,希望对大家的学习有所帮助。