继承一个对象的功能

问题:当创建一个对象类型时,想要从已有的对象继承功能
解决方案:使用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);//true
console.log(obj instanceof newObject);//true
console.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());//6
console.log(obj.getVal1());//1
console.log(obj.getVal2());//2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值