'use strict';// User 类class User { constructor(name,age) { this.name = name; this.age = age; } static getName() { return 'User'; } static getAge() { return this.age; } setName(name) { this.name = name; } setAge(age) { this.age = age; } get info() { return 'name:' + this.name + ' | age:' + this.age; }}// Manager 类class Manager extends User{ constructor(name,age,password){ super(name,age); this.password = this.password; } changePwd(pwd) { return this.password = pwd; } get info() { var info = super.info; // 使用super继承父级 get return info + ' === new'; }}// typeof User: function typeof Manager: functionconsole.log('typeof User: ', typeof User, ' typeof Manager: ', typeof Manager); let manager = new Manager('Li', 22, '123456');manager.setAge(23);console.log(manager.info); // name:Li | age:23 === newconsole.log(User.prototype);console.log(Manager.prototype);
// 构造函数function User(name,age) { this.name = name; this.age = age;}// 原型User.prototype = { getName:function(){ return 'User'; }, setName:function(name){ this.name = name; }, getAge:function(){ return this.age; }, setAge:function(age){ this.age = age; }}// 取值函数和存执函数Object.defineProperty(User.prototype,'info', { get() { return 'name:' + this.name + ' | age:' + this.age; }});var user = new User('Joh', 26);console.log(user); // User {name: "Joh", age: 26}// 子类function Manager(name, age, password) { User.call(this, name, age); this.password = password;}Manager.__proto__ = User; // 继承静态方法Manager.prototype = Object.create(User.prototype); // 继承prototype原型方法Manager.prototype.changePwd = function (pwd) { this.password = pwd;};var manager = new Manager('Li', 22, '123456');manager.setAge(23);console.log(manager.info); // name:Li | age:23console.log(User.prototype); // 不变console.log(Manager.prototype); // {changePwd:function(){}, info:"name:undefined | age:undefined", __proto__:指向Manager.prototype}