Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. function Person(name){
  2. this.name = name
  3. }
  4.  
  5. Person.prototype.sayHello = function(){
  6. console.log(`Hello ${this.name}`)
  7. }
  8.  
  9. function Employee(name,dept){
  10. // construcotr 的 prototype 的 constructor 會指會自己
  11. Employee._super.constructor.call(this,name)
  12. this.dept = dept
  13. }
  14.  
  15. Employee.prototype.selfIntroduction = function(){
  16. //改成從 Property 中去讀
  17. Employee._super.sayHello.call(this)
  18. console.log(`In the ${this.dept} department`)
  19. }
  20.  
  21. const subclass = (subC,superC) => {
  22. //處理prototype
  23. let subProto = Object.create(superC.prototype)
  24. //將原本 subC.prototype 的 Property 定義給 subProto (這裡和複製物件時用的方式相同)
  25. const arrOwnProperties = Object.getOwnPropertyNames(subC.prototype)
  26. arrOwnProperties.forEach( property => {
  27. const prototypeDesc = Object.getOwnPropertyDescriptor(subC.prototype,property)
  28. Object.defineProperty(subProto,property,prototypeDesc)
  29. })
  30. //將處理完後的 prototype 給 subC 的 protoype
  31. subC.prototype = subProto
  32. //定義 _super Property 為父類別的 prototype
  33. subC._super = superC.prototype
  34. }
  35.  
  36. //設定 Person 和 Employee 為父子類別
  37. subclass(Employee,Person)
  38.  
  39. const mary = new Employee('Mary','IT')
  40.  
  41. mary.selfIntroduction()
  42. //會同時列出
  43. /*
  44. Hello Mary
  45. In the IT department
  46. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement