Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Person(name){
- this.name = name
- }
- Person.prototype.sayHello = function(){
- console.log(`Hello ${this.name}`)
- }
- function Employee(name,dept){
- // construcotr 的 prototype 的 constructor 會指會自己
- Employee._super.constructor.call(this,name)
- this.dept = dept
- }
- Employee.prototype.selfIntroduction = function(){
- //改成從 Property 中去讀
- Employee._super.sayHello.call(this)
- console.log(`In the ${this.dept} department`)
- }
- const subclass = (subC,superC) => {
- //處理prototype
- let subProto = Object.create(superC.prototype)
- //將原本 subC.prototype 的 Property 定義給 subProto (這裡和複製物件時用的方式相同)
- const arrOwnProperties = Object.getOwnPropertyNames(subC.prototype)
- arrOwnProperties.forEach( property => {
- const prototypeDesc = Object.getOwnPropertyDescriptor(subC.prototype,property)
- Object.defineProperty(subProto,property,prototypeDesc)
- })
- //將處理完後的 prototype 給 subC 的 protoype
- subC.prototype = subProto
- //定義 _super Property 為父類別的 prototype
- subC._super = superC.prototype
- }
- //設定 Person 和 Employee 為父子類別
- subclass(Employee,Person)
- const mary = new Employee('Mary','IT')
- mary.selfIntroduction()
- //會同時列出
- /*
- Hello Mary
- In the IT department
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement