來源:前端全棧君丶 發(fā)布時間:2018-12-04 14:01:01 閱讀量:1227
封裝Encapsulation
如下代碼,這就算是封裝了
(function (windows, undefined) {
var i = 0;//相對外部環(huán)境來說,這里的i就算是封裝了
})(window, undefined);
1
2
3
繼承Inheritance
(function (windows, undefined) {
//父類
function Person() { }
Person.prototype.name = "name in Person";
//子類
function Student() { }
Student.prototype = new Person(); //修復(fù)原型
Student.prototype.constructor = Student; //構(gòu)造函數(shù)
Student.prototype.supr = Person.prototype; //父類
//創(chuàng)建子類實例
var stu = new Student();
Student.prototype.age = 28;
Student.prototype.name = "name in Student instance";
//打印子類成員及父類成員
console.log(stu.name); //name in Student instance
console.log(stu.supr.name); //name in Person
console.log(stu.age); //28
})(window, undefined);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
前端全棧學(xué)習(xí)交流圈:866109386,面向1-3經(jīng)驗?zāi)昵岸碎_發(fā)人員,幫助突破技術(shù)瓶頸,提升思維能力
運行結(jié)果如下:
多態(tài)Polymorphism
有了繼承,多態(tài)就好辦了
//這就是繼承了
(function (windows, undefined) {
//父類
function Person() { }
Person.prototype.name = "name in Person";
Person.prototype.learning = function () {
console.log("learning in Person")
}
//子類
function Student() { }
Student.prototype = new Person(); //修復(fù)原型
Student.prototype.constructor = Student; //構(gòu)造函數(shù)
Student.prototype.supr = Person.prototype; //父類
Student.prototype.learning = function () {
console.log("learning in Student");
}
//工人
function Worker() { }
Worker.prototype = new Person(); //修復(fù)原型
Worker.prototype.constructor = Worker; //構(gòu)造函數(shù)
Worker.prototype.supr = Person.prototype; //父類
Worker.prototype.learning = function () {
console.log("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);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
運行結(jié)果如下:
---------------------