四种继承方法
准备一个父类 function Father(){ this.name = 'jack'; this.age = 20; } Father.prototype.fun1 = function(){ console.log(this.name + '-' + this.age); } 1.原型继承 function Son(){ this.sex = 'man'; } Son.prototype = new Father(); //将子类的原型指向父类实例或者构造函数 const son = new Son(); son.fun1() // 结果为:undefined-undefined无法继承到父类的属性
2.借用继承 function Son(){ Father.call(this); //使用call/apply将父类指向子类 } const son = new Son();无法继承到父类prototype上的属性
3.组合继承 function Son(){ this.sex = 'man'; Father.call(this); //使用call/apply将父类指向子类 } Son.prototype = new Father(); //将子类的原型指向父类实例或者构造函数 const son = new Son(); son.fun1() // 输出结果为:jack - 20结合了两种方法,解决两种方法的缺点
ES6继承 extends class Father{ constructor(){ this.name = 'jack'; this.age = 20; } fun1(){ console.log(this.name + '-' + this.age); } } class Son extends Father{ constructor(name,age){ super(name,age); //继承父类的属性,使用super定义 } }可以继承父类的所有属性方法
不同的对象执行同一操作,返回不同结果。
function Person(name,age){ this.name = name; var age = age; this.show = function(){ console.log(this.name+"-"+age); } } const xiaoming = new Person('小明',20); const lihua = new Person('李华',18); xiaoming.show(); //输出结果为:小明-20 lihua.show(); //输出结果为:李华-18promise的出现主要是解决回调地狱问题,比如 ajax 请求 你的 ajax 请求需要另外一个请求的结果作为参数来发送请求,这样就需要一层套一层,有了 promise 就无需嵌套。本质就是分离异步数据获取和业务逻辑。
const p1 = new Promise(function(resovle,reject){ //接收两个参数 resovle 执行成功 reject 执行失败 if(异步执行成功){ resolve('success'); }else{ reject('error'); } }); //当这个 promise 状态发生改变(执行了 resolve 或 reject)就会触发 then()响应处理函数处理后续步骤 // 执行失败则会出入到 catch 中 p1.then(res=>console.log(res)). catch(err=>console.log(err)); Promise.all([p1,p2]).then() 所有promise都完成resovled 才算完成回调。只要有一个reject,回调失败,返回第一个失败的结果。Promise.any([p1,p2]) 只要其中的promise有一个完成,就返回那个已经完成的promise(所有都reject了),就返回一个拒绝的promise。Promise.race([p1,p2])返回最先执行完成的promise,无论是resovle还是reject。get请求
var xhr = null; //兼容IE处理 if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveObject('Microsoft.XMLHTTP'); } xhr.open('get',url,async); xhr.send(); xhr.onload = function(){ console.log(xhr.response); }post请求
var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveObject('Microsoft.XMLHTTP'); } xhr.open('post',url,async); xhr.setRequestHeader("content-Type","application/x-www-form-urlencoded"); xhr.send(args); // 发送请求传递的参数 xhr.onload = function(){ console.log(xhr.response); }原型链 当访问一个对象的某个属性时,会先对这个对象的本身属性上查找,如果没有,则会去它的__proto__隐式原型上找,即它的构造函数的 prototype,如果还没有找到,就会在构造函数的 prototype 的 proto 中查找,这样一层层向上查找就会形成一个链结构
三次握手 1.客户端向服务端发送一个数据包。 2.服务端收到后,回传一个数据包表示确认收到。 3.客户端收到回传一个数据包,握手结束,建立连接。 四次挥手 1.主动关闭放向被动关闭方发送一个数据包,告诉被动方,我要与你断开连接了,但我还可以接收数据。 2.被动关闭方收到后,回传一个数据包表示收到。 3.被动方发送一个包,告诉主动方我发送完就不会再发送数据了,但可以接收数据。 4.主动方收到后,发送一个确认收到