单体模式
单体模式
单体模式
1 2 3 4 5 6 7 8
| var Teacher = { name: "fei", age: 18, showName: function () { return this.name; } }; Teacher.showName();
|
原型模式
1 2 3 4 5 6 7 8 9 10 11
| function Teacher(name, age) { this.name = name; this.age = age; }
Teacher.prototype.showName = function () { return this.name; };
var foo = new Teacher('fei', 18); foo.showName();
|
伪类模式—建议使用ES6
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Teacher { constructor(name, age) { this.name = name; this.age = age; }
showName() { return this.name; } }
var foo = new Teacher('fei', 18); foo.showName();
|
面向对象继承
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
| var Teacher = { name: "fei", age: 18, showName: function () { return this.name; } }; var student = Object.create(Teacher); student.name = "foo"; student.showName();
var Teacher = { name: "fei", age: 18, showName: function () { return this.name; } }; var student = Object.create(Teacher); student.name = "foo"; student.age = 20; student.showName(); student.showAge = function (age) { return this.age; }; student.showAge();
|
xxxx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Person{ constructor(name, age) { this.name = name; this.age = age; }
showName() { return this.name; } }
class Teacher extends Person { constructor(name,age,job) { super(name,age); this.job = job; }
showInfo() { return this.job + "___" + super.showName(); } }
var foo = new Teacher("fei",18,"WEB"); foo.showInfo("WEB");
|
对象原型 prototypes