标签:
把所有信息封装在构造函数内,通过在构造函数中初始化原型,保持了同时使用构造函数和原型的优点,通过检查某个应该存放的方法是否有效,来决定是否需要初始化原型。(通过if判断)
function Person(name,age,job){
this.name=name;
this.age-age;
this.job=job;
//判断方法是否存在
if(typeof this.sayName!="function"){
Person.prototype.sayName=function(){
alert(this.name);
};
}
}
var friend=new Person("Nicholas",30,"Engineer");
friend.sayName();
注意:使用动态原型模式时,不能使用对象字面量重写原型,会切断实例与新原型之间的联系;使用这种模式可以使用isstanceof操作符确定创建对象的类型。
标签:
原文地址:http://www.cnblogs.com/zhouchuanming/p/5861480.html