4.使用prototype原型对象定义类成员
使用prototype对象来定义类成员可以避免每实例化一个对象就创建一次类成员的缺点。
当new一个function时,prototype对象的成员将自动赋给所创建的对象。
Demo2:
是一个JavaScript对象,可以为prototype对象添加、修改、删除方法和属性。从而为一个类添加成员定义。















prototype
了解了函数的prototype对象,现在再来看new的执行过程。
1>创建一个新的对象,并让this指针指向它;
2>将函数的prototype对象的所有成员都赋给这个新对象;
3>执行函数体,对这个对象进行初始化操作;
4>返回(1)中创建的对象。
prototype对象的所有成员初始化过程发生在函数体(构造器)执行之前,所以可以在函数体内部调用prototype中定义的属性和方法。
Demo3:











和上一段代码相比,这里在cls的内部调用了prototype中定义的方法showcaption,从而在对象的构造过程中就弹出了对话框,显示caption属性的值为1。
需要注意,原型对象的定义必须在创建类实例的语句之前,否则它将不会起作用。
Demo4:
showcaption方法,就是因为该方法的定义是在实例化一个类的语句之后。














这段代码将会产生运行时错误,显示对象没有
由此可见,prototype对象专用于设计类的成员,它是和一个类紧密相关的。
除此之外,prototype还有一个重要的属性:constructor,表示对该构造函数的引用,例如:





这段代码运行后将会出现对话框,在上面显示文字“1”,从而可以看出一个prototype是和一个类的定义紧密相关的。
实际上:cls.prototype.constructor===cls。
Read: 776