js高级第三天
1.es5属性的继承
call
关键代码:Person.call(this,name, color, height);
call修改父类Person的this指向为子类构造函数的实例(this)
第二个参数开始为向父类Person传参
function Person(name, color, height) {
this.name = name;
this.color = color;
this.height = height;
}
function YellowPerson(name, color, height, nickname, gender) {
// 父亲中也有
Person.call(this,name, color, height);// 属性的继承
// 儿子
this.nickname = nickname;
this.gender = gender;
}
2.es5方法的继承
Person父类原型赋值给Student子类原型就实现了子类继承父类方法
再修改子类原型的构造器指向为子类的构造函数
// 赋值了父类原型上的所有的 属性和方法
Student.prototype = Person.prototype;
// 修改子类的指向
Student.prototype.constructor = Student;
3.es6的class
es6的class 的出现 基本上可以替代了es5的构造函数和原型,使之代码结构上更加简洁
extends继承
super如果子类继承了父类,且子类需要使用constructor接收参数,则必须使用super调用父类的构造器为子类添加相同属性
class Person {
constructor(name, color) {
this.name = name;
this.color = color;
}
}
class YellowPerson extends Person {
// 默认的代码
constructor(name, color, height, weight) {
super(name, color);// 调用父亲的构造器 给儿子 添加属性
this.height = height;
this.weight = weight;
}
}
const yp = new YellowPerson('悟空', '黄色', 100, 200);
console.log(yp);
instanceof
检测某个实例是不是被某个构造函数 new 出来的
class Person {}
class SuperPerson{}
const p1 = new Person();
const s1 = new SuperPerson();
console.log(p1 instanceof Person);// true
console.log(p1 instanceof SuperPerson); // false
this指向
事件中的this
事件中的this指向事件源
单独使用时
this
指向全局对象
console.log(this);
全局作用域下的函数中的this
在全局作用域下定义的函数本质是挂载到window上,调用时本质是window.fn()
window省略,所以全局函数中this指向window
function fn(){
console.log(this);// 指向window
}
fn();
方法内部的this
当一个函数被保存为对象的一个属性时,我们称之为一个方法。
方法中this
的指向在方法定义的时候是不能确定的,只有方法被调用后才能确定,方法调用后this指向调用者
const obj = {
sayHi:function(){
console.log(this);//在方法调用模式中,this指向调用者
}
}
obj.sayHi();//this指向obj
构造函数的this
如果函数是通过new关键字进行调用的,此时this指向创建出来的实例上。
function Person(){
console.log(this);
}
Person();//this指向window
const p = new Person();//this指向实例p
this指向小案例
const age = 38;
const obj = {
age: 18,
getAge: function () {
console.log(this.age);
}
}
const f = obj.getAge;
f();// this指向window
const age = 38;
const obj = {
age:18,
getAge:function () {
console.log(this.age);// obj
function foo(){
console.log(this.age);// window
}
foo();
}
}
obj.getAge();
上下文调用模式call apply bind
call和apply方法中, this指向方法内的第一个参数
bind方法中, bind创建的新函数的this绑定为bind方法中新的函数
定时器和延时器中的this
定时器中,this指向window
setTimeout
中传入函数时,函数中的this会指向window对象
但是在setTimeout
中传入的不是函数时,this则指向当前对象
箭头函数的this
箭头函数中没有this指向问题,它的this和外层作用域的this保持一致
匿名函数的this
匿名函数中的this总是指向window