创建对象的方式(2)
原型模式
先看下面的例子:
function Student(name,age){
this.name = name;
Student.prototype.age = 22;
Student.prototype.say = function(){
console.log(this.name);
}
}
var student1 = new Student('lisi',20);
var student2 = new Student('san',20);
var b = student1.say;
上述的例子student1与student2调用的是原型对象上的函数,而这个函数只会被创建一次
原型模式
先看下面的例子:
function Student(name,age){
this.name = name;
Student.prototype.age = 22;
Student.prototype.say = function(){
console.log(this.name);
}
}
var student1 = new Student('lisi',20);
var student2 = new Student('san',20);
var b = student1.say;
var c = student1.say;
1.我们在Student这个函数里面定义了Student.prototype.age,Student.prototype.say,其表示在这个函数的原型上定义了一个属性及方法
2.student1与student2调用的say都是指向同一个函数,即Student原型上定义的方法函数
上述的例子student1与student2调用的是原型对象上的函数,而这个函数只会被创建一次