封裝Encapsulation 如下代碼,這就算是封裝了 (function (windows, undefined) { var i = 0;//相對外部環境來說,這裡的i就算是封裝了 })(window, undefined); 繼承Inheritance (function (windows, ...
封裝Encapsulation
如下代碼,這就算是封裝了
(function (windows, undefined) {
var i = 0;//相對外部環境來說,這裡的i就算是封裝了
})(window, undefined);
繼承Inheritance
(function (windows, undefined) {
//父類
function Person() { }
Person.prototype.name = "name in Person";
//子類
function Student() { }
Student.prototype = new Person(); //修複原型
Student.prototype.constructor = Student; //構造函數
Student.prototype.supr = Person.prototype; //父類
//創建子類實例
var stu = new Student();
Student.prototype.age = 28;
Student.prototype.name = "name in Student instance";
//列印子類成員及父類成員
alert(stu.name); //name in Student instance
alert(stu.supr.name); //name in Person
alert(stu.age); //28
})(window, undefined);
多態Polymorphism
有了繼承,多態就好辦了
//這就是繼承了
(function (windows, undefined) {
//父類
function Person() { }
Person.prototype.name = "name in Person";
Person.prototype.learning = function () {
alert("learning in Person")
}
//子類
function Student() { }
Student.prototype = new Person(); //修複原型
Student.prototype.constructor = Student; //構造函數
Student.prototype.supr = Person.prototype; //父類
Student.prototype.learning = function () {
alert("learning in Student");
}
//工人
function Worker() { }
Worker.prototype = new Person(); //修複原型
Worker.prototype.constructor = Worker; //構造函數
Worker.prototype.supr = Person.prototype; //父類
Worker.prototype.learning = function () {
alert("learning in Worker");
}
//工廠
var personFactory = function (type) {
switch (type) {
case "Worker":
return new Worker();
break;
case "Student":
return new Student();
break;
}
return new Person();
}
//客戶端
var person = personFactory("Student");
person.learning(); //learning in Student
person = personFactory("Worker");
person.learning(); //learning in Worker
})(window, undefined);
閱讀原文請點擊此處