<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA_Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script>
window.onload = function () {
// call()
// 调用这个函数,并且修改函数运行时的this指向
// fun.call(thisArg, Arg1, Arg2, ...)
// thisArg:当前调用函数this的指向对象
// arg1 , arg2:传递的其他参数
// call方法
//1.
function fn() {
console.log("Hello World!");
}
fn();//Hello World
fn.call();//Hello World
function fn2() {
console.log(this)
}
fn2();//Window
fn2.call();//Window
//call() 可以改变这个函数的this指向
function fn3(x,y) {
console.log(x,y);
console.log(this)
}
var o = {
name:'andy'
};
fn3(1,2);
//1 2
//Window
fn3.call(o,1,2);//此时这个函数的 this 就指向了 o 这个对象。1 传给 x,2传给 y。
// 1 2
// Object
// name: "andy"
// __proto__: Object
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++");//分割线
//借用父构造函数继承属性
//1.父构造函数
function Father(name,age) {
// this 指向父构造函数的对象实例
this.name = name;
this.age = age;
}
//2.子构造函数
function Son(name,age,score) {
// this 指向子构造函数的对象实例
Father.call(this,name,age);//将父构造函数的 this 修改为子构造函数的 this 。
this.score = score;
}
var son = new Son('jzw',27,99);
console.log(son);
// Son
// age: 27
// name: "jzw"
// score: 99
// __proto__: Object
//用父构造函数继承方法
//1.父构造函数
function Father1(name,age) {
// this 指向父构造函数的对象实例
this.name = name;
this.age = age;
}
Father1.prototype.money = function () {
console.log("一月两千块!");
};
//2.子构造函数
function Son1(name,age,score) {
// this 指向子构造函数的对象实例
Father1.call(this,name,age);//将父构造函数的 this 修改为子构造函数的 this 。
this.score = score;
}
Son1.prototype.exam = function () {
console.log("考试考了99分!");
};
var son1 = new Son1('jzw',27,99);
console.log(son1);//输出并没有将money方法输出。
//为什么呢?
//因为 money 方法是写在原型对象(Father.prototype)里,没有写在构造函数(Father)里面
//而我们的操作都是在调用构造函数,没有调用原型对象,所以找不到这个方法。
//解决方法:
//1.父构造函数
function Father2(name,age) {
// this 指向父构造函数的对象实例
this.name = name;
this.age = age;
}
Father2.prototype.money = function () {
console.log("一月两千块!");
};
//2.子构造函数
function Son2(name,age,score) {
// this 指向子构造函数的对象实例
Father2.call(this,name,age);//将父构造函数的 this 修改为子构造函数的 this 。
this.score = score;
}
Son2.prototype = new Father2();
//如果利用对象的形式修改了原型对象,别忘了利用 constructor 指回原来的构造函数
Son2.prototype.constructor = Son2;
Son2.prototype.exam = function () {
console.log("考试考了99分!");
};
var son2 = new Son2('jzw',27,99);
console.log(son2);//输出并没有将money方法输出。
}
</script>
</head>
<body>
</body>
</html>
call继承
猜你喜欢
转载自blog.csdn.net/weixin_45949073/article/details/107430336
今日推荐
周排行