es6之前没有给我们提供extends继承。我们可以通过构造函数+原型对象模拟实现继承,被称为组合继承。
使用call()函数继承
1.call() 调用这个函数,并且修改这个函数运行时的this指向。
语法:call(thisobj,arg1,arg2,...)
thisobj:当前调用函数this的指向对象。
arg1,arg2传递的其他参数。
2.call()可以改变函数的this指向
//call方法
function fn (x, y) {
console.log('我想喝咖啡');
console.log(this);
console.log(x + y);
}
var o = {
name: 'andy'
}
//1.call可以调用函数
// fn.call()
//2.call可以改变这个函数的this指向 此时这个函数的this 就指向了o这个对象
fn.call(o, 1, 2)
控制台输出如下:
借用构造函数继承父类型属性
//借用父构造函数继承属性
//父构造函数
function Father (uname, age) {
this.uname = uname
this.age = age
}
function Son (uname, age, score) {
//把父构造函数的this 该成子构造函数的this
//这里的this是Son这个构造函数,所以就把Father这个构造函数的this指向改成了Son的this指向
Father.call(this, uname, age)
this.score = score
}
var son = new Son('刘德华', 18, 100)
console.log(son);
利用原型对象继承父类型方法:
//借用父构造函数继承属性
//父构造函数
function Father (uname, age) {
this.uname = uname
this.age = age
}
Father.prototype.money = function () {
console.log('爸爸今天挣了100000');
}
//继承方法 不能通过简单的原型对象的赋值来实现 因为在这里自构造函数指向了父构造函数 就是把父构造函数的地址给了子构造函数 所以在对自构造函数的原型对象进行修改时 也会对父构造函数产生影响 即父元素对象也会拥有与子元素对象一样的变化
//Son.prototype = Father.prototype
Son.prototype = new Father()
//如果利用对象的形式修改了原型对象, 别忘了利用constructor 指回原来的构造函数
Son.prototype.constructor = Son
function Son (uname, age, score) {
//把父构造函数的this 该成子构造函数的this
//这里的this是Son这个构造函数,所以就把Father这个构造函数的this指向改成了Son的this指向
Father.call(this, uname, age)
this.score = score
}
Son.prototype.exam = function () {
console.log('100分');
}
var son = new Son('刘德华', 18, 100)
console.log(son);
console.log(Son.prototype.constructor);