组合使用构造函数模型和原型模型中的问题,使用对象字面量重写原型模型会有隐患(涉及到原型的动态性),如下例:
<!DOCTYPE html>
<html>
<head>
<title>组合使用构造函数模型和原型模型——问题</title>
<script type="text/javascript">
//组合使用构造函数模型和原型模型——构造函数模型用于定义实例属性,原型模型用于定义方法和共享属性。
function Student(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
this.friends=["Kitty","Court"];
}
//该方式出错
// var stu1=new Student("Lucy",10,"girl");
// Student.prototype={
// constructor:Student,
// sayName:function(){
// alert(this.name);
// }
// }
// stu1.sayName(); //使用对象字面量重写原型模型,出错
var stu2=new Student("Bob",9,"boy");
Student.prototype.sayName=function(){
alert(this.name);
};
stu2.sayName();
</script>
</head>
<body>
</body>
</html>
在学习动态原型模型时,发现书中标注“使用动态原型模型时,不能使用对象字面量重写原型。”,于是想到组合方式中就是使用对象字面量重写原型模型的,于是就验证是否有问题,所以写个小心得,避免以后犯错。