Guest User

Untitled

a guest
May 23rd, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. if(typeof Object.create!='function'){
  2. Object.create = function(o){
  3. var F = function(){};
  4. F.prototype = o;
  5. return new F();
  6. }
  7. }
  8. var o = Object.create(a)
  9.  
  10.  
  11.  
  12.  
  13.  
  14. /**********/
  15.  
  16. function inheritPrototype(subType,superType){
  17. // 两个参数:子类型构造函数和超类型构造函数
  18.  
  19. var prototype = object(superType.prototype);
  20. // 创建超类型原型的副本
  21.  
  22. prototype.constructor = subType;
  23. // 为副本添加constructor属性,弥补重写原型失去默认constructor属性
  24.  
  25. subType.prototype = prototype;
  26. // 创建的新对象赋值给子类型的原型
  27. }
  28.  
  29.  
  30.  
  31.  
  32.  
  33. /*********/
  34.  
  35.  
  36. function extend(base, sub) {
  37.  
  38. var origProto = sub.prototype;
  39. sub.prototype = Object.create(base.prototype);
  40. for (var key in origProto) {
  41. sub.prototype[key] = origProto[key];
  42. }
  43. // Remember the constructor property was set wrong, let's fix it
  44. sub.prototype.constructor = sub;
  45. // In ECMAScript5+ (all modern browsers), you can make the constructor property
  46. // non-enumerable if you define it like this instead
  47. Object.defineProperty(sub.prototype, 'constructor', {
  48. enumerable: false,
  49. value: sub
  50. });
  51. }
  52.  
  53. // Let's try this
  54. function Animal(name) {
  55. this.name = name;
  56. }
  57.  
  58. Animal.prototype = {
  59. sayMyName: function() {
  60. console.log(this.getWordsToSay() + " " + this.name);
  61. },
  62. getWordsToSay: function() {
  63. // Abstract
  64. }
  65. }
  66.  
  67. function Dog(name) {
  68. // Call the parent's constructor
  69. Animal.call(this, name);
  70. }
  71.  
  72. Dog.prototype = {
  73. getWordsToSay: function(){
  74. return "Ruff Ruff";
  75. }
  76. }
  77.  
  78. // Setup the prototype chain the right way
  79. extend(Animal, Dog);
  80.  
  81. // Here is where the Dog (and Animal) constructors are called
  82. var dog = new Dog("Lassie");
  83. dog.sayMyName(); // Outputs Ruff Ruff Lassie
  84. console.log(dog instanceof Animal); // true
  85. console.log(dog.constructor); // Dog
Add Comment
Please, Sign In to add comment