1. call()
call()
可以调用函数call()
可以修改this
的指向,使用call()
的时候,参数一是修改后的this
指向,参数2,参数3…使用逗号隔开连接
function fn(x, y) {
console.log(this);
console.log(x + y);
}
var usr = {
name: 'Jack'
};
fn();
fn.call(usr, 1, 2);

2. 子构造函数继承父构造函数中的属性
- 先定义一个父构造函数
- 再定义一个子构造函数
- 子构造函数继承父构造函数的属性(使用
call()
方法)
function Father(uname, age) {
this.uname = uname;
this.age = age;
}
function Son(uname, age, score) {
Father.call(this, uname, age);
this.score = score;
}
var son = new Son('Jack', 18, 100);
console.log(son);

3. 借用原型对象继承方法
- 先定义一个父构造函数
- 再定义一个子构造函数
- 子构造函数继承父构造函数的属性(使用
call()
方法)
function Father(uname, age) {
this.uname = uname;
this.age = age;
}
Father.prototype.money = function() {
console.log(100000);
};
function Son(uname, age, score) {
Father.call(this, uname, age);
this.score = score;
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
Son.prototype.exam = function() {
console.log('孩子要考试');
}
var son = new Son('Jack', 18, 100);
console.log(son);
