原型(prototype)实现继承
rototype 即为原型,每一个对象 ( 由 function 定义出来 ) 都有一个默认的原型属性,该属性是个对象类型。 并且该默认属性用来实现链的向上攀查。意思就是说,如果某个对象的属性不存在,那么将通过prototype属性所属对象来查找这个属性。如果 prototype 查找不到呢? js会自动地找prototype的prototype属性所属对象来查找,这样就通过prototype一直往上索引攀查,直到查找到了该属性或者prototype最后为空 (“undefined”);
function Person(name,age){ this.name=name; this.age=age; } Person.prototype.sayHello=function(){ alert("使用原型得到Name:"+this.name); } var per=new Person("马小倩",21); per.sayHello(); //输出:使用原型得到Name:马小倩 function Student(){} Student.prototype=new Person("洪如彤",21); var stu=new Student(); Student.prototype.grade=5; Student.prototype.intr=function(){ alert(this.grade); } stu.sayHello();//输出:使用原型得到Name:洪如彤 stu.intr();//输出:5
构造函数实现继承
function Parent(name){ this.name=name; this.sayParent=function(){ alert("Parent:"+this.name); } } function Child(name,age){ this.tempMethod=Parent; this.tempMethod(name); this.age=age; this.sayChild=function(){ alert("Child:"+this.name+"age:"+this.age); } } var parent=new Parent("江剑臣"); parent.sayParent(); //输出:“Parent:江剑臣” var child=new Child("李鸣",24); //输出:“Child:李鸣 age:24” child.sayChild();
3.call , apply实现继承
方法定义
call方法:
语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]]) 定义:调用一个对象的一个方法,以另一个对象替换当前对象。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。
apply方法:
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另一个对象替换当前对象。
说明: 如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。
实例
unction add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add.call(sub,3,1);
实现继承
function Person(name,age,love){ this.name=name; this.age=age; this.love=love; this.say=function say(){ alert("姓名:"+name); } } //call方式 function student(name,age){ Person.call(this,name,age); } //apply方式 function teacher(name,love){ Person.apply(this,[name,love]); //Person.apply(this,arguments); //跟上句一样的效果,arguments } //call与aplly的异同: //1,第一个参数this都一样,指当前对象 //2,第二个参数不一样:call的是一个个的参数列表;apply的是一个数组(arguments也可以) var per=new Person("武凤楼",25,"魏荧屏"); //输出:“武凤楼” per.say(); var stu=new student("曹玉",18);//输出:“曹玉” stu.say(); var tea=new teacher("秦杰",16);//输出:“秦杰” tea.say();