ES6以前並無給咱們提供extends繼承。咱們能夠經過構造函數+原型對象模擬實現繼承,被稱爲組合繼承函數
調用這個函數而且修改函數運行時的this指向this
fun. call (thisArg, arg1, arg2, ...)spa
thisArg : 當前調用函數this的指向對象prototype
arg1 , arg2 :傳遞的其餘參數對象
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var o = {
name: 'andy'
};
fn.call(o, 1, 2);//調用了函數此時的this指向了對象o,
call()能夠調用函數blog
call()能夠修改this的指向,使用call()的時候 參數一是修改後的this指向,參數2,參數3..使用逗號隔開鏈接繼承
核心原理:經過call()把父類型的this指向子類型的this , 這樣就能夠實現子類型繼承父類型的屬性。原型
先定義一個父構造函數string
再定義一個子構造函數it
子構造函數繼承父構造函數的屬性(使用call方法)
// 1. 父構造函數
function Father(uname, age) {
// this 指向父構造函數的對象實例
this.uname = uname;
this.age = age;
}
// 2 .子構造函數
function Son(uname, age, score) {
// this 指向子構造函數的對象實例
//3.使用call方式實現子繼承父的屬性
Father.call(this, uname, age);
this.score = score;
}
var son = new Son('劉德華', 18, 100);
console.log(son);
// 1. 父構造函數
function Father(uname, age) {
// this 指向父構造函數的對象實例
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log(100000);
};
// 2 .子構造函數
function Son(uname, age, score) {
// this 指向子構造函數的對象實例
//3.使用call方式實現子繼承父的屬性
Father.call(this, uname, age);
this.score = score;
}
// Son.prototype = Father.prototype; 這樣直接賦值會有問題,若是修改了子原型對象,父原型對象也會跟着一塊兒變化
Son.prototype = new Father();
// 若是利用對象的形式修改了原型對象,別忘了利用constructor 指回原來的構造函數
Son.prototype.constructor = Son;
// 這個是子構造函數專門的方法
Son.prototype.exam = function() {
console.log('孩子要考試');
}
var son = new Son('劉德華', 18, 100);
console.log(son);
如上代碼結果如圖: