JavaScript中類的創建、繼承,類的隱藏及實例化

alert("類的隱藏");


//異常拋出
try{
//(function(){}()),先是一個(),然後括號裏帶一個方法,然後再加上一個()執行
//這是一個隱藏的實現,這樣的話 ,有利於保護一些數據被篡改
(function(){
var str = "But";
//建立一個People的方法
function People(name){
this._name = name;
}


//People類裏的一個say()方法
People.prototype.say = function(){
alert("People - Hello-"+this._name+str);
}


//把People對象傳遞給Windows
window.People = People;
}());

(function(){


//學生類方法
function Student(name){
this._name = name;
}


//學生類繼承People
Student.prototype = new People();
//保存之前父類的say()方法
var superSay = Student.prototype.say;
//學生類的say()方法
Student.prototype.say = function(){
//調用的是之前父類裏面的say()方法
superSay.call(this);
//輸出
alert("Student - Hello-"+this._name);
//這時的str就是隱藏的,所以這樣的話會提示 str is not define
alert(str);
}
window.Student = Student;
}());

//創建一個學生類的實例
var s = new Student("Astor");
s.say();//輸出的是:People - Hello-AstorBut和Student - Hello-Astor
}catch(err){
alert(err);
}
發佈了88 篇原創文章 · 獲贊 32 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章