继承一个对象的功能

来源:互联网 发布:临沂知豆电动汽车销售 编辑:程序博客网 时间:2024/06/06 21:38

问题:当创建一个对象类型时,想要从已有的对象继承功能
解决方案:使用Object.create()方法

function origObject(){  this.val1 = 'a';  this.val2 = 'b';}origObject.prototype.returnVal1 = function(){  return this.val1;}origObject.prototype.returnVal2 = function(){  return this.val2;}function newObject(){  this.val3 = 'c';  origObject.call(this);}newObject.prototype = Object.create(origObject.prototype);newObject.prototype.constructor = newObject;newObject.prototype.returnValues=function(){  return this.val1 + this.val2 + this.val3;}var obj = new newObject();console.log(obj instanceof origObject);//trueconsole.log(obj instanceof newObject);//trueconsole.log(obj.returnValues());//"abc"

说明
+ Object.create()第一个参数充当了新创建对象的原型对象,第二个参数可选,等于Object.defineProperties()中的第二个参数
+ call()和apply()方法:每个函数都包含这两个非继承方法
+ 用途:在特定的作用域中调用函数,实际上等于设置函数体内的this值
+ apply()接收两个参数:参数1:是其中运行函数的作用域;参数2:参数数组(可以是Array的实例,也可以是arguments对象)
+ 区别在于 call方法的第一个参数是this值没变,变化的是其余参数都是直接传递给函数,使用call方法时,若写参数列表,则要一一罗列。而apply方法第二个参数是数组。

将上面的代码改写,使用apply方法

function origObject(val1,val2){  this.getVal1 = function(){    return val1;  }  this.getVal2 = function(){    return val2;  }}function newObject(val1,val2,val3){   this.getVal3 = function(){     return val3;   }  origObject.apply(this,arguments);  this.getValues = function(){    return this.getVal1()+this.getVal2()+val3;  }}newObject.prototype = Object.create(origObject.prototype);newObject.prototype.constructor = newObject;var obj = new newObject(1,2,3);console.log(obj.getValues());//6console.log(obj.getVal1());//1console.log(obj.getVal2());//2
阅读全文
0 0
原创粉丝点击