js prototype屬性使用程式碼例項

antzone發表於2017-04-03

關於prototype屬性的用法這裡不多介紹了,具體可以參閱javascript prototype原型一章節。 

下面就分享一段關於prototype屬性使用的程式碼例項,需要的朋友可以做一下參考。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
//定義函式
function people(name,sex,age){ 
  this.name = name;
  this.sex = sex;
  this.age = age;
}
  
//共享isStudent與sayName方法
people.prototype = {  
  isStudent:true,
  sayName:function(){
    console.log(this.name);
  }
}
  
var people1 = new people('softwhy','女',20);  //例項化物件1
var people2 = new people('antzone','男',17);    //例項化物件2
  
//通過共享的方法讓兩個物件說出自己的名字
people1.sayName(); 
people2.sayName();
  
//通過共享的引數判斷他們都是學生
if(people1.isStudent == people2.isStudent){
  console.log('螞蟻部落歡迎您');
}

相關文章