|
| 1 | +function Animal(){ |
| 2 | + this.type = "animal"; |
| 3 | + |
| 4 | + //实现抽象类 |
| 5 | + if(new.target === Animal){ |
| 6 | + throw new Error("animal不可被实例化"); |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +// let animal = new Animal();//报错 |
| 11 | + |
| 12 | +Animal.prototype.say = function(){ |
| 13 | + console.log("say.."); |
| 14 | +} |
| 15 | + |
| 16 | +//实现父类与子类的继承 |
| 17 | +function Tiger(){ |
| 18 | + Animal.call(this);//继承了父类的实例属性和方法 |
| 19 | +} |
| 20 | + |
| 21 | +//继承父类原型上的属性和方法 |
| 22 | +//(1) Tiger.prototype = Animal.prototype;//指向了同一个原型对象,子类原型的修改会影响到父类原型 |
| 23 | + |
| 24 | +/* |
| 25 | +(2)修改子类的__proto__指向父类的prototype |
| 26 | + 1)因为Tiger与Animal是两个不同的类,且之间没有new的关系,而且在原型上没有__proto__的指向关系,因此需要手动修改Animal类__proto__指向Animal.prototype |
| 27 | + 2)低版本浏览器中可能不识别__proto__ |
| 28 | +*/ |
| 29 | + |
| 30 | +//Es5中的方法,利用了原型链,将Tiger的原型的原型指向Animal.prototype |
| 31 | +// Tiger.prototype.__proto__ = Animal.prototype; |
| 32 | + |
| 33 | +//ES6中提供的方法 |
| 34 | +// Object.setPrototypeOf(Tiger.prototype,Animal.prototype); |
| 35 | + |
| 36 | +/* |
| 37 | +(1)使用Object.create()改变子类的prototype |
| 38 | +(2)这种方式会导致子类指向一个实例对象,而实例对象自身无constructor属性,向上找到父类prototype上的constructor属性,因此需要手动修改子类prototype上constructor的指向 |
| 39 | +*/ |
| 40 | + |
| 41 | +// Tiger.prototype = Object.create(Animal.prototype); |
| 42 | + |
| 43 | +//增加constructor指向的参数 |
| 44 | +// Tiger.prototype = Object.create(Animal.prototype,{"constructor":{value:Tiger}}); |
| 45 | + |
| 46 | +//模拟实现Object.create() |
| 47 | +function create(parentPrototype){ |
| 48 | + let Fn = function(){}; |
| 49 | + //构建一个中间类指向父类,Tiger自身的prototype的属性和方法都写在中间类Fn的prototype上 |
| 50 | + Fn.prototype = parentPrototype; |
| 51 | + // return new Fn(); |
| 52 | + |
| 53 | + //改进:给实例添加一个constructor的属性,修正constructor的指向 |
| 54 | + let fn = new Fn(); |
| 55 | + fn.constructor = Tiger; |
| 56 | + return fn; |
| 57 | +} |
| 58 | + |
| 59 | +Tiger.prototype = create(Animal.prototype); |
| 60 | + |
| 61 | +let tiger = new Tiger; |
| 62 | + |
| 63 | +console.log(tiger.type);//animal |
| 64 | +tiger.say();//say.. |
| 65 | +console.log(tiger.constructor)//[Function:Animal],修正指向前;[Function:Tiger],修正指向后 |
| 66 | + |
| 67 | +//类的静态属性 |
| 68 | +Tiger.a = 10; |
| 69 | +console.log(Tiger.a);//10 |
| 70 | + |
| 71 | +//类的静态方法 |
| 72 | +Tiger.eat = function(){ |
| 73 | + console.log('eat..'); |
| 74 | +} |
| 75 | +Tiger.eat();//eat.. |
0 commit comments