前言以上对原型和原型链做了一些简单的概念介绍和分析。本文将简要分析一些原型链的扩展。javaScript原型和原型链http://lewyon.xyz/prototype.html扩展原型链使用new操作符来利用原型作为对象的特性。实例化一个对象时,继承多个构造函数的属性和方法兼容性:支持当前和所有可以想象的浏览器(IE5.5works)functionparent1(){}parent1.prototype={parentName:"parent1",};functionparent2(){}letchild=newparent1();child.childName="child";parent2.prototype=child;letnewChild=newparent2();console.log(newChild.parentName);//parent1console.log(newChild.childName);//child使用Object.createObject.createObject.create()方法创建一个新对象并使用现有对象提供新创建对象的proto兼容性:支持当前所有非Microsoft版本或IE9/**以上版本的浏览器**Object.create(proto,[propertiesObject])**@paramsproto新建对象的原型对象。*如果proto参数不为null或者非原始包装对象,抛出TypeError异常,可以使用try和catch来捕获抛出的异常**@paramspropertiesObject可选参数,数据类型:object***/constparent1={name:"parent1",do:function(){console.log(this.name);},};constchild=Object.create(parent1);child.name="child";//child添加自己的属性namechild.do();//孩子/******-----------------------------------------------------------------****/functionparent2(){}parent2.prototype={name:"parent2",};functionparent3(){}letchild=Object.create(parent2.prototype);child.childName="child";parent3.prototype=child;letnewChild=newparent3();console.log(newChild.name);//parent2console.log(newChild.childName);//child使用setPrototypeOf兼容性:不支持IE8及以下版本。/***Object.setPrototypeOf(obj,prototype)**@paramsobj要设置其原型的对象。**@paramsprototype**对象的新原型(一个对象或null)*如果要设置其原型的对象的[[Prototype]]被修改为不可扩展(通过Object.isExtensible()查看)抛出)TypeError异常。*如果原型参数的数据类型不是object或null(例如number、string、boolean或undefined),那么该方法将不会被执行。*否则,该方法将obj的[[Prototype]]修改为新值。**Object.setPrototypeOf()是ECMAScript6中的一个新方法,相对于操作对象的原型链Object.prototype.__proto__,更适合修改对象的原型。****/functionparent1(){}parent1.prototype={name:"parent1",};functionparent2(){}letObj={ObjName:"Obj",};Object.setPrototypeOf(Obj,parent1.原型);parent2.prototype=Obj;让newChild=newparent2();console.log(newChild.name);//parent1console.log(newChild.ObjName);//Obj使用__proto__直接操作原型链,使用__proto__操作,如果设置的属性和方法较多,会造成性能问题,所以不建议使用__proto__兼容性:IE10及以下浏览器版本。/****直接在原型链上操作。如果设置了很多属性和方法,就会出现性能问题。***/varobj={__proto__:{protoName1:"protoName1",__proto__:{protoName2:"protoName2",__proto__:Object.prototype,},},};控制台日志(obj.protoName1);//protoName1console.log(obj.protoName2);//protoName1总结在使用原型链编写组件的过程中,我们需要考虑到原型链的性能问题。在实例化对象的过程中,会向上查找原型链的方法和属性。在写的过程中需要注意对象自带的构造函数和方法,确认是否会被覆盖重写。以上就是对js中扩展原型链的简单分析。有问题欢迎留言,后续文章会整理补充。文章博客地址:JavaScript扩展原型链分析源码地址码云https://gitee.com/lewyon/vue-notegithubhttps://github.com/akari16/vue-note欢迎关注公众号:程序员布欧,不时更新一些文章并不容易。转载请注明出处和作者。
