1、函數(shù)的調(diào)用方式
既可以使用函數(shù)名+()的形式調(diào)用,也可以使用函數(shù)名+call()的形式調(diào)用;
兩種調(diào)用方式的區(qū)別:1)小括號調(diào)用:如果向小括號中傳參,則該參數(shù)一定是函數(shù)所需要的參數(shù);2)call()調(diào)用:如果向call的小括號中傳參,則參數(shù)一定是一個對象,call會把所調(diào)函數(shù)中的this指針指到該參數(shù)上。
call和apply的區(qū)別:功能上一模一樣;在用法上:apply在傳遞函數(shù)所需參數(shù)時,使用數(shù)組結(jié)構(gòu)傳遞
// hello.call(per, 'hello', '12', 34);
// hello.apply(per, ['hello', '12', 34]);
2、原型鏈方式實現(xiàn)繼承
function CreateAnimal(name,age){this.name = name;this.age = age;}
function CreatePerson(name,age,gender){this.gender = gender;}
//把父級的對象當(dāng)做子級的原型對象,這樣父級就和子級建立了聯(lián)系(通過父級對象的__proto__屬性):
CreatePerson.prototype = new CreateAnimal('zhangsan',18);
//因為父級對象下的constructor屬性指向的是創(chuàng)造它的函數(shù),但是原型對象的constructor屬性又必須指向創(chuàng)造它的原型的構(gòu)造函數(shù):所以要修改constructor的指針指向。
CreatePerson.prototype.constructor = CreatePerson;
var per = new CreatePerson('zhangsan',18,'man');
console.log(per);
3、組合繼承
組合繼承:即為使用call/apply實現(xiàn)對實例屬性的繼承,使用原型實現(xiàn)對原型方法的繼承
function CreateAnimal(name,age){this.name = name;this.age = age;}
CreateAnimal.prototype.sayHi = function(){alert('hello';)}
function CreatePerson(name,age,gender){CreateAnimal.call(this,name,age); this.gender = gender;}
CreatePerson.prototype = new CreateAnimal();
CreatePerson.prototype.constructor = CreatePerson;
CreatePerson.prototype.eatFoot = function () {alert('吃飯了');}
var per = new CreatePerson('zhengSan', 18, 'man');
// console.log(per.gender);
per.sayHi();