js继承的几种方式
原型链继承:无法传参
function Fun1(){ this.property = true; } Fun1.prototype.getValue = function(){ return this . property; } Function Fun2(){ this.sub = false; } Fun2.prototype = new Fun1(); Fun2.prototype .sayValue = function(){ return this.sub; } Var instance = new Fun2(); Console.log(instance.getValue()); // 创建Fun1的实例,并讲该实例赋给Fun2.prototype实现的。本质是重写原型对象,代之以一个新类型的实例。原来存在于Fun1的实例中的属性和方法,现在也存在于Fun2.prototype中了。
构造函数:call() apply() 解决传参的问题,父类原型的属性和方法不能继承,实例不是父类的实例
function Fun1(){ this.color=[‘red’ , ’blue’]; } function Fun2(){ fun1.call(this); } var instance1 = new Fun2(); Instance1.colors.push(“black”); Console.log(instance1.colors); //red blue black Var instance2 = new Fun2(); Console.log(instance2.colors); // red blue 传参: Function Fun1(name){ this.name = name; } Function Fun2(age){ Fun2.call(this, “John”); This.age = 23; } Var instance = new Fun2(); Console.log(instance.name)// John Console.log(instance.age)//23
组合继承:组合原型链和构造函数,原型链实现对原型属性和方法的继承,构造函数来实现对实例属性的继承。
Function Fun1(name){ This.name = name; This.color = [“red” , “blue”]; } Fun1.prototype.sayName = function(){ alert(this.name); } Function Fun2(name , age){ Fun1.call(this , name); This.age = age; } Fun2.prototype = new Fun1(); Fun2.prototype.sayAge = function(){ Console.log(this.age); } Var instance1= new Fun2(“John”, 29); Instance1.colors.push(“black”); Console.log(instance1.colors); //red blue black Instance1.sayName (); //John Instance1.sayAge(); // 29 Var instance2 = new Fun2(); Console.log(Instance2.color); //red blue Instance.sayName();//John Instance.sayAge(); //29
原型式继承:借助原型可以基于已有的对象创建新对象,同时还不必须因此创建自定义的类型。
//新增Object.create()方法规范了原型式继承 //可以传递两个参数,第一个是用作新对象原型的对象,第二个(可选)为新对象定义额外属性的对象 //传递一个参数时,等同于object() var person = { name:"EvanChen", friends:["Shelby","Court","Van"]; }; var anotherPerson = Object.create(person); anotherPerson.name = "Greg"; anotherPerson.friends.push("Rob"); var yetAnotherPerson = Object.create(person); yetAnotherPerson.name = "Linda"; yetAnotherPerson.friends.push("Barbie"); console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie"
思想: function object(o) { function F(){ } F.prototype = o; return new F(); } var person = { name:"EvanChen", friends:["Shelby","Court","Van"]; }; var anotherPerson = object(person); anotherPerson.name = "Greg"; anotherPerson.friends.push("Rob"); var yetAnotherPerson = object(person); yetAnotherPerson.name = "Linda"; yetAnotherPerson.friends.push("Barbie"); console.log(person.friends);//"Shelby","Court","Van","Rob","Barbie" //必须有一个对象作为另一个对象的基础,如果有这么一个对象的话,可以传递给object()函数,然后该函数就会返回一个新的对象