原型和原型链
- 原型分为隐式原型和显式原型,每个对象都有一个隐式原型,它指向自己的构造函数的显式原型
- 原型链:多个_proto_组成的集合成为原型链
- 所有实例的_proto_都指向他们构造函数的prototype
- 所有的prototype都是对象,自然它的_proto_指向的是object()的prototype
- 所有的构造函数的隐式原型指向的都是function()的显示原型
注:object的隐式原型是null

instanceof
- instanceof 运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。(判断继承关系)
- 可以判断继承关系,只要是在同一条原型链上,就可以返回true

class Person {
constructor(name){
this.name = name;
}
}
class Student extends Person {
constructor(name,age){
super(name);
this.age = age;
}
}
const zhangsan = new Student("张三",18);
console.log(myInstanceof(zhangsan,Student));
console.log(myInstanceof(zhangsan,Person));
console.log(myInstanceof(zhangsan,Object));
console.log(myInstanceof(zhangsan,Array));
function myInstanceof(obj1,obj2) {
let obj1Proto = obj1.__proto__;
while(true){
if(obj1Proto === null){
return false;
}
if(obj1Proto === obj2.prototype){
return true;
}
obj1Proto = obj1Proto.__proto__;
}
}
this指向
- 非严格模式 this -> window
function a () {
console.log(this);
}
a()
- 严格模式 this -> undefined
"use strict"
function a() {
console.log(this);
}
a()
- 情况一:this->window
1) a.call()
2) a.call(undefined)
3)a.call(null)
function a (){
console.log(this);
}
a.call(null/undefined)
- 情况二:传什么,this就是什么
function a (){
console.log(this);
}
const fn = a.bind({x:101});
fn()
- 情况一:定时器+function this -> window
function fn(){
setTimeout(function(){
console.log(this);
},100)
}
fn.call({x:101})
- 情况二:定时器+箭头函数 this -> 上层作用域的this
class obj {
fn(){
setTimeout(()=>{
console.log(this);
},100)
}
}
const o = new obj();
o.fn();
- 情况一:有function作用域的,this是上层作用域的this(new一个作用域)
class obj {
say = () => {
console.log(this);
}
}
const obj1 = new obj();
obj1.say()
- 情况二:没有function作用域的,this是window
const obj2 = {
say:()=>{
console.log(this);
},
}
obj2.say();