JavaScript实现继承
- 原型链
- 基本思想:利用原型让一个引用类型继承另一个引用类型的属性和方法
- 构造函数,原型和实例三者之间的关系:每一个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针(constructor属性,这个属性包含一个指向prototype属性所在的函数指针,而实例都包含一个指向原型对象的内部指针)12345678910111213141516//原型链function SuperType(){this.property=true;}SuperType.prototype.getSuperValue=function(){return this.property;};function SubType(){this.subproperty=false;}SubType.prototype=new SuperType();SubType.prototype.getSubValue=function(){return this.subproperty;}var instance=new SubType();console.log(instance.getSuperValue());
借用构造函数
123456789101112131415借用构造函数function SuperType(){this.colors=["red","blue","green"];}function Subtype(){SuperType.call(this);//实现继承}var instance1=new Subtype();instance1.colors.push("black");console.log(instance1.colors);//["red", "blue", "green", "black"]var instance2=new Subtype();console.log(instance2.colors);["red", "blue", "green"]借用构造函数传递参数的情况
1234567891011121314传递参数function SuperType(name){this.name=name;}function SubType(){SuperType.call(this,"chenyu");this.age=29;}var instance=new SubType();console.log(instance.name);//chenyuconsole.log(instance.age);29组合继承
1234567891011121314151617181920212223242526组合继承function SuperType(name){this.name=name;this.colors=["red","blue","green"];}SuperType.prototype.sayName=function(){console.log(this.name);};function SubType(name,age){SuperType.call(this,name);this.age=age;}//继承方法SubType.prototype=new SuperType();SubType.prototype.constructor=SubType;SubType.prototype.sayAge=function(){console.log(this.age);}var instance1=new SubType("chenyu",20);instance1.colors.push("black");console.log(instance1.colors);//"red", "blue", "green", "black"]instance1.sayName();//chenyuinstance1.sayAge();//20寄生式继承
12345678910111213141516171819202122232425262728293031323334353637寄生式继承function object(o){function F(){}//临时性的构造函数F.prototype=o;//吧传入的参数给构造函数的原型return new F();//返回函数创造的新实例}var person={name:"chenyu",friends:["haha","enen","yeye"]}//创建两个person的副本对其对象进行修改var anotherPerson=object(person);anotherPerson.name="chenyu";anotherPerson.friends.push("bob");var anotherPerson1=object(person);anotherPerson1.name="chenqian";anotherPerson1.friends.push("fighting");console.log(person.friends);//["haha", "enen", "yeye", "bob", "fighting"]> //es5的Object.creat()方法实现寄生式继承。原理与object()方法的效果一样var person={name:"chenyu",friends:["yulin","langxiaoju","wnagju","chenzihan"]};var anotherPerson=Object.create(person);anotherPerson.name="a";anotherPerson.friends.push("zeze");console.log(person.friends);var anotherPerson1=Object.create(person);anotherPerson1.name="b";anotherPerson1.friends.push("enen");console.log(person.friends);console.log(person.name);console.log(anotherPerson1.name);