Javascript:必须知道的Javascript知识点之“原型链”
Javascript:必须知道的Javascript知识点之“this指针”
1 var Base = function (name) { 2 this.name = name; 3 }; 4 5 var base = new Base(); 6 7 console.log((base instanceof Object));//true 8 console.log((base instanceof Base));//true 9 console.log(Base.prototype.isPrototypeOf(base));//true 10 console.log(Object.prototype.isPrototypeOf(base));//true 11 console.log(base.hasOwnProperty("name"));//true 12 console.log(base.hasOwnProperty("toString"));//false 13 console.log(("name" in base));//true 14 console.log(("toString" in base));//true
1 Function.prototype.extend = function (baseType) { 2 var tempType = function () { }; 3 tempType.prototype = baseType.prototype; 4 5 this.prototype = new tempType(); 6 this.prototype.constructor = this; 7 this.super = function () { 8 return baseType.prototype; 9 }; 10 }; 11 12 var Base = function (name) { 13 this.name = name; 14 }; 15 16 var Animal = function () { 17 Animal.super().constructor.apply(this, arguments); 18 }; 19 Animal.extend(Base); 20 21 var Dog = function () { 22 Dog.super().constructor.apply(this, arguments); 23 }; 24 Dog.extend(Animal); 25 26 var dog = new Dog('笨狗'); 27 console.log(dog.name);//笨狗 28 console.log(dog instanceof Base);//true 29 console.log(dog instanceof Animal);//true 30 console.log(dog instanceof Dog);//true
问题:为什么要引入“tempType”,而不是直接“this.prototype = new baseType()”?
答案:“new baseType()”会导致构造方法被调用两次。
问题:为什么不直接“this.prototype = baseType.prototype”?
答案:这样的话,父子类型就会同时指向一个prototype,不符合继承的语义。
参考文章:设计原则:请重新审视“多重继承”,找机会拥抱一下“掺入(Mixin)”。
1 Function.prototype.extend = function (baseType) { 2 var tempType = function () { }; 3 tempType.prototype = baseType.prototype; 4 5 this.prototype = new tempType(); 6 this.prototype.constructor = this; 7 this.super = function () { 8 return baseType.prototype; 9 }; 10 }; 11 12 var Base = function (name) { 13 this.name = name; 14 }; 15 16 var Animal = function () { 17 Animal.super().constructor.apply(this, arguments); 18 }; 19 Animal.extend(Base); 20 21 var Dog = function () { 22 Dog.super().constructor.apply(this, arguments); 23 }; 24 Dog.extend(Animal); 25 26 var dog = new Dog('笨狗'); 27 console.log(dog.name);//笨狗 28 console.log(dog instanceof Base);//true 29 console.log(dog instanceof Animal);//true 30 console.log(dog instanceof Dog);//true 31 32 Function.prototype.mixin = function (name, mixinType) { 33 this.mixins = {}; 34 this.mixins[name] = mixinType; 35 36 for (var property in mixinType.prototype) { 37 if (property in this.prototype) { 38 continue; 39 } 40 41 this.prototype[property] = mixinType.prototype[property]; 42 } 43 }; 44 45 var Pet = function () { 46 }; 47 Pet.prototype.aoao = function () { 48 console.log(this.name + ',嗷嗷!'); 49 }; 50 51 Dog.mixin('pet', Pet); 52 dog.aoao(); 53 console.log(dog instanceof Pet);//false
问题:这种掺入实现是不是太简单了?
答案:确实,但是能满足80%的需求,掺入的主要目的就是代码复用。
由于“原型链”的限制,Javascript实现不了真正意义的“多重继承”。