js構(gòu)造函數(shù)的繼承
1call()
(1) call()可以調(diào)用函數(shù)
(2) call()可以修改this的指向,使用call()的時候 參數(shù)一是修改后的this指向,參數(shù)2,參數(shù)3..使用逗號隔開連接
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var xhc = {
name: 'andy'
};
fn.call(xhc, 1, 2);//調(diào)用了函數(shù)此時的this指向了對象xhc,
2子構(gòu)造函數(shù)繼承父構(gòu)造函數(shù)中的屬性
- 先定義一個父構(gòu)造函數(shù).
- 再定義一個子構(gòu)造函數(shù)
- 子構(gòu)造函數(shù)繼承父構(gòu)造函數(shù)的屬性(使用call方法)
// 1. 父構(gòu)造函數(shù)
function Father(uname, age) {
// this 指向父構(gòu)造函數(shù)的對象實例
this.uname = uname;
this.age = age;
}
// 2 .子構(gòu)造函數(shù)
function Son(uname, age, score) {
// this 指向子構(gòu)造函數(shù)的對象實例
// 3.使用call方式實現(xiàn)子繼承父的屬性
Father.call(this, uname, age);
this.score = score;
}
var son = new Son('kunkun', 18, 100);
console.log(son);
3借用原型對象繼承方法 (組合繼承)
- 先定義一個父構(gòu)造函數(shù)
- 再定義一個子構(gòu)造函數(shù)
- 子構(gòu)造函數(shù)繼承父構(gòu)造函數(shù)的屬性(使用call方法)
// 1. 父構(gòu)造函數(shù)
function Father(uname, age) {
// this 指向父構(gòu)造函數(shù)的對象實例
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log(1111111);
};
// 2 .子構(gòu)造函數(shù)
function Son(uname, age, score) {
// this 指向子構(gòu)造函數(shù)的對象實例
Father.call(this, uname, age);
this.score = score;
}
// Son.prototype = Father.prototype; 這樣直接賦值會有問題,如果修改了子原型對象,父原型對象也會跟著一起變化
Son.prototype = new Father();
// 如果利用對象的形式修改了原型對象,別忘了利用constructor 指回原來的構(gòu)造函數(shù)
Son.prototype.constructor = Son;
// 這個是子構(gòu)造函數(shù)專門的方法
Son.prototype.exam = function() {
console.log(2222222);
}
var son = new Son('kunkun', 18, 100);
console.log(son);