第一种,prototype的方式:
//父类 function person(){ this.hair = 'black'; this.eye = 'black'; this.skin = 'yellow'; this.view = function(){ return this.hair + ',' + this.eye + ',' + this.skin; } } //子类 function man(){ this.feature = ['beard','strong']; } man.prototype = new person(); var one = new man(); console.log(one.feature); //['beard','strong'] console.log(one.hair); //black console.log(one.eye); //black console.log(one.skin); //yellow console.log(one.view()); //black,black,yellow
这种方式最为简单,只需要让子类的prototype属性值赋值为被继承的一个实例就行了,之后就可以直接使用被继承类的方法了。
prototype 属性是啥意思呢? prototype 即为原型,每一个对象 ( 由 function 定义出来 ) 都有一个默认的原型属性,该属性是个对象类型。
并且该默认属性用来实现链的向上攀查。意思就是说,如果某个对象的属性不存在,那么将通过prototype属性所属对象来查找这个属性。如果 prototype 查找不到呢?
js会自动地找prototype的prototype属性所属对象来查找,这样就通过prototype一直往上索引攀查,直到查找到了该属性或者prototype最后为空 (“undefined”);
例如上例中的one.view()方法,js会先在one实例中查找是否有view()方法,因为没有,所以查找man.prototype属性,而prototype的值为person的一个实例,
该实例有view()方法,于是调用成功。
第二种,apply的方式:
//父类 function person(){ this.hair = 'black'; this.eye = 'black'; this.skin = 'yellow'; this.view = function(){ return this.hair + ',' + this.eye + ',' + this.skin; } } //子类 function man(){ // person.apply(this,new Array()); person.apply(this,[]); this.feature = ['beard','strong']; } var one = new man(); console.log(one.feature); //['beard','strong'] console.log(one.hair); //black console.log(one.eye); //black console.log(one.skin); //yellow console.log(one.view()); //black,black,yellow
注意:如果apply参数为空,即没有参数传递,则通过 new Array() 、[] 来传递,null 无效。
第三种,call+prototype的方式:
//父类 function person(){ this.hair = 'black'; this.eye = 'black'; this.skin = 'yellow'; this.view = function(){ return this.hair + ',' + this.eye + ',' + this.skin; } } //子类 function man(){ // person.apply(this,new Array()); person.call(this,[]); this.feature = ['beard','strong']; } man.prototype = new person(); var one = new man(); console.log(one.feature); //['beard','strong'] console.log(one.hair); //black console.log(one.eye); //black console.log(one.skin); //yellow console.log(one.view()); //black,black,yellow
call方式的实现机制却要多一条 man.prototype = new person(); 为啥呢?
新闻热点
疑难解答
图片精选