我们在JS中有时会需要定义一个类,下面会通过构造函数的方法来定义一个类
例如
function Student(name, number)
{
this.name=name;
this.number=number;
var scores=[];
this.info=function(){
return "name: "+name+" "+"number: "+number;
}
this.scores=function(){
scores[counter]=0;
counter++;
}
}
Student.prototype={
run:function(){return "run";},
sleep:function(){return "sleep";},
info2:function(){return name+" "+number}
}
var stu1=new Student("zhangsan","1001");
console.log(stu1.info());
console.log(stu1.run());
console.log(stu1.sleep());
console.log(stu1.info2());
这其中在Student的构造函数声明的方法及在Student.prototype中声明的方法,均可作为类的成员函数来调用,那他们的区别在哪里呢?
第一:
在构造函数中定义的变量或者方法,当类实例化一个对象时,这个对象就会复制一份构造函数里面的内容,如果当类实例化很多对象时会相当耗内存。
第二:
为了解决这种消耗,Student.prototype中定义的每一个方法,在类实例化对象时,方法不会被复制,也就是说所有对象中的Student.prototype中的方法仅占用一份内存,里面的方法为所有对象共享。这个机制很像c++类中的成员函数存放行为
class Student{
public:
void memberFunction1(){return;}
void memberFunction2(){return;}
private:
int m_iX;
int m_iY;
}
当C++类实例化对象时,数据成员均会被复制,但是成员函数不会,一个类无论有多少对象,所有对象的成员函数均在同一块内存地址。