OO for JS - 如何在JS寫面向對像?
inheritanceManager = {}; inheritanceManager.extend = function(subClass,baseClass){ function inheritance(){}; inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); subClass.prototype.constructor = subClass; subClass.baseConstructor = baseClass; subClass.superClass = baseClass.prototype; } Person = function(id,name,age){ this.id = id; this.name=name; this.age=age; } Person.prototype = { wakeUp : function(){ console.log('Wake up'); }, getAge : function(){ return this.age; } } Manager = function(id, name, age, salary){ Manager.baseConstructor.call(this, id, name, age); this.salary = salary; console.log('Manager has been registered'); } inheritanceManager.extend(Manager, Person); Manager.prototype.lead = function(){ console.log('Lead is great lead'); } let p = new Person('0','andy',20,2000); let pm = new Manager('0','andy',50,3000); console.log(p) console.log(pm) console.log(p) Person = function(id, name, age){ this.id = id; this.name = name; this.age = age; console.log('A new person has been accepted'); } Person.prototype = { /** wake person up */ wake_up: function() { console.log('I am awake'); }, /** retrieve person's age */ get_age: function() { return this.age; } } Inheritance_Manager = {}; Inheritance_Manager.extend = function(subClass, baseClass) { function inheritance() { } inheritance.prototype = baseClass.prototype; subClass.prototype = new inheritance(); subClass.prototype.constructor = subClass; subClass.baseConstructor = baseClass; subClass.superClass = baseClass.prototype; } Manager = function(id, name, age, salary) { Manager.baseConstructor.call(this, id, name, age); this.salary = salary; console.log('A manager has been registered.'); } Inheritance_Manager.extend(Manager, Person); Manager.prototype.lead = function(){ console.log('I am a good leader'); } var p = new Person(1, 'Joe Tester', 26); var pm = new Manager(1, 'Joe Tester', 26, '20.000'); console.log(pm); pm.age = 10; console.log(pm);
Published 6 Sep 2017