Simplest class
function Person() { this.name = 'lisi'; this.age = 20; } var p = new Person(); alert(p.name);
Add methods to constructor and prototype chain
function Person() { this.name = 'lisi'; this.age = 20; this.run = function() { alert(this.name + 'In sports'); } } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } var p = new Person(); alert(p.name); p.run(); p.work()
Static methods in class
function Person() { this.name = 'lisi'; this.age = 20; this.run = function() { alert(this.name + 'In sports'); } } Person.getInfo = function() { alert('I'm a static method') } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } var p = new Person(); // p.work(); Person.getInfo()
Inheritance in es5, the object pretends to implement inheritance
There is only one pop-up box, indicating that there is no method inherited to prototype
function Person() { this.name = 'lisi'; this.age = 20; this.run = function() { alert(this.name + 'In sports'); } } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } //Web class inherits Person class function Web() { Person.call(this); } var w = new Web(); w.run(); w.work();
Inheritance in es5, prototype chain implementation inheritance
function Person() { this.name = 'lisi'; this.age = 20; this.run = function() { alert(this.name + 'In sports'); } } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } //Web class inherits Person class function Web() { } Web.prototype = new Person(); var w = new Web(); w.run(); w.work();
On the inheritance of prototype chain
function Person(name, age) { this.name = name; this.age = age; this.run = function() { alert(this.name + 'In sports'); } } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } function Web(name, age) { } Web.prototype = new Person(); var w = new Web('lisi', 20) w.run() w.work()
The combination inheritance pattern of prototype chain and object impersonation
function Person(name, age) { this.name = name; this.age = age; this.run = function() { alert(this.name + 'In sports'); } } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } function Web(name, age) { Person.call(this, name, age); } Web.prototype = new Person(); var w = new Web('lisi', 20) w.run() w.work()
Another way of prototype chain + object impersonation
function Person(name, age) { this.name = name; this.age = age; this.run = function() { alert(this.name + 'In sports'); } } Person.prototype.sex = 'male'; Person.prototype.work = function() { alert(this.name + 'At work'); } function Web(name, age) { Person.call(this, name, age); } Web.prototype = Person.prototype; var w = new Web('lisi', 20) w.run() w.work()