js原型二

时间:2024-10-04 11:06:38
 function Box(name,age){

    this.name = name;

    this.age = age;

    this.family = ['哥哥',‘姐姐’,‘妹妹’];

 }

 Box.prototype = {

    constructor:Box,

    run:functiong(){
return this.name+this.age+"运行中" }
}
var box1 = new Box("Lee",100); var box2 = new Box("Jack",200);

组合构造函数+原型模式

使用动态原型模式

 function Box(name,age){
this.name = name;
this.age = age;
this.family = ['哥哥',‘姐姐’,‘妹妹’];
if(typeof this.run !="function"){ //判断this.run是否存在
Box.prototype.run=function(){
return this.name+this.age+"运行中"
}
}
}
//原型的初始化只要第一次初始化就可以了,没必要每次构造函数实例化的时候都初始化。
var box1 = new Box("Lee",100)
var box2 = new Box("Jack",200)