js继承的方式
原型链继承
function Parent(){ this.name='mike'; this.age=12; } function Child(){ } //儿子继承父亲(原型链) Child.prototype=new Parent();//Child继承Parent,通过原型形成链条 var test=new Child(); console.log(test.age); console.log(test.name);//得到被继承的属性 //孙子继续原型链继承儿子 function Brother(){ this.weight=60; } Brother.prototype=new Child();//继承原型链继承 var brother=new Brother(); console.log(brother.name);//继承了Parent和Child,弹出mike console.log(brother.age);//12 console.log(brother.weight); //instanceof 就是判断一个实例是否属于某种类型 console.log(brother instanceof Child);//ture console.log(brother instanceof Parent);//ture console.log(brother instanceof Object);//ture
call和apply函数的继承
call和apply都可以实现函数的继承
function Parent(age){ this.name=['mike','jack','smith']; this.age=age; } function Child(age){ Parent.call(this,age);//让Child拥有Parent的属性 Parent.apply(this,[age]); } var test=new Child(21); console.log(test.age);//21 console.log(test.name); test.name.push('bill'); console.log(test.name);//mike,jack,smith,bill
call和apply的区别是穿的参数不同
call和apply都接收两个参数,第一个参数都是thisobj
apply的第二个参数必须是有效数组或arguments对象
call的第二个参数必须列举出来
var myObject = {firstName:'my', lastName:'Object'}; function getMessage(sex,age){ console.log(this.firstName + this.lastName + " 性别: " + sex + " age: " + age ); } getMessage.apply(myObject,["未知",22]);//myObject 性别: 未知 age: 22 getMessage.call(myObject,"未知",22);//myObject 性别: 未知 age: 22
记录生活中的点点滴滴!