js原型
有没有接触过java的继承,复用父类的方法,js如何解决这个问题?
-
why什么添加原型
- 将方法添加构造函数本身,不是所有实例都需要,会造成大量内存空间浪费,相反,如果将方法添加到原型中,只需将它放到内存中一个位置,但都可以访问
- 实现继承,调用父类方法
-
原型的规则(结合案列说明)
-
所有引用类型(数组、对象、函数)都具有对象的特性,可以自有扩展属性
-
所有的引用类型都具有_proto_(隐式原型),属性值是一个普通对象
-
所有函数都有一个prototype(显式原型),属性值也是一个普通对象
-
所有引用类型(数组、对象、函数)的_proto_属性(隐式原型)都指向其构造函数的prototype(显式原型)属性
-
当试图得到一个对象某个属性和方法时,如果这个对象没有,那么回去它的_proto_(隐式原型)即为其构造函数的显式原型中查找
-
一般情况下,属性定义到构造函数中,公共方法定义到原型对象
function Foo(name){ this.name=name; } Foo.prototype.sayName=function(){ console.log(this.name) } const foo=new Foo('hashiqi') foo.sayName() // hashiqi
-
辨认是否是自身属性 obj.hasOwnProperty(‘key’)
insert -
foo instance of Foo: 查找foo._proto _ 能否找到Foo.prototype
-
-
原型的案列
function Elem(id){ this.elem=document.getElementById(id); } Elem.prototype.html=function(val){ const elem=this.elem; if(val){elem.innerHtml = val;return this } else{ return elem.innerHtml } } Elem.prototype.on=function(type,fn){ const elem=this.elem; elem.addEventListener(type,fn) return this } const el=new Elem('detail') div.html('<p>world</p>').on('click',()=>{alert()})
Array.prototype.sum=function(){ let sum=0; for(let i=0;i<this.length;i++){ sum+=sum + this[i] } return sum }