天天看點

建立對象的方式(2)

建立對象的方式(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;

var c = student1.say;

console.log(b===c);//傳回的是true

1.我們在Student這個函數裡面定義了Student.prototype.age,Student.prototype.say,其表示在這個函數的原型上定義了一個屬性及方法

2.student1與student2調用的say都是指向同一個函數,即Student原型上定義的方法函數

我們建立的函數都有一個prototype屬性,而這個屬性是一個指針,指向一個對象即原型對象

上述的例子student1與student2調用的是原型對象上的函數,而這個函數隻會被建立一次

繼續閱讀