前端面试总结——原型和原型链

1.class

class People {
  constructor(name)
  {this.name=name;}
  eat(){
    console.log(this.name+'is eating something')
  }
}
const zhangsan=new People(张三);
console.log(zhangsan.name);
zhangsan.eat();
class Student extends People{
constructor(name,number){
   super(name);
   this.number=number;
}
study(){
console.log(this.name+'is learning');
  }
}
const lihua=new Student(李华,100);
console.log(lihua.name);
console.log(lihua.number);
lihua.eat();
lihua.study();

2.原型关系

每个class都有显式原型prototype

每个实例都有隐式原型_proto_

实例的_proto_指向对应class的显式原型

class.prototype===example._proto_

3.基于原型的执行规则

获取属性和方法时,

先在对象本身的方法和属性里查找

如果没有找到,就到对象的_proto_中查找

4.手写简易的jQuery

class jQury{
      constructor(selector){
        let result=document.querySelectorAll(selector);
        let len=result.length;
        this.length=len;
        for(let i=0;i{
     elem.addeventListener(type,fn,false);
})
}
}

5.手写代码

创建10个a标签,点击的时候弹出对应的序列号

let a;
for(let i=0;i<10;i++){
a=document.creatElement('a');
a.innerHtml=i+'
' a.addEventListener('click',function(e){ e.preventDeafault() alert(i) }) document.body.appendChild(a); }

6.this

fn1(){ console.log(this);}

fn1();//this指向window

fn1().call({x:100});//{x:100}

const fn2=fn1.bind({x:200});

fn2();//{x:200}

const zhangsan={
  name:'张三',
  sayhi(){
  console.log(this);//zhangsan},
  wait(){settimeout(
  function{console.log(this);//window}
  )}
}

const zhangsan={
 name:'张三',
sayhi(){
console.log(this);//zhangsan},
waitagain(){
settimeout(()=>{
console.log(this);//zhangsan
})
}
}

class People{
constructor(name){
this.name=name;
this.age=age;
}
sayhi(){
console.log(this);
}
}
const zhangsan=new People('张三');
zhangsan.sayhi();//zhangsan对象

总结:

1.当作普通函数被调用,this指向window

2.使用call,apply,bind,this指向call,apply,bind所绑定的对象

3.作为对象的方法调用,this指向该对象

4.在class的方法中调用,this指向class创建的实例

5.箭头函数的this指向上级作用域的this

7.手写bind

Function.prototype.mybind=function(){
let args=Array.prototype.slice.call(arguments);
const t=args.shift();
const self=this;
return function(){
return self.apply(t,args);
}
}

8.闭包的实际应用

//闭包隐藏数据,只提供API
function createCahe(){
  const data={};//data中的数据,不被外界访问
return{
set:function(key,value){
  data[key]=value;
}
get:function(key){
  return data[key];
    }
  }
}

const c=createCahe();
c.set('a',100);
c.get('a');

你可能感兴趣的:(前端)