对象的继承

对象的继承


 function MyArray() {}  //声明一个MyArray函数
 MyArray.prototype = new Array(); //将MyArray的原型对象赋值为Array的实例
 MyArray.prototype.constructor = MyArray; //将MyArray的constructor赋值为MyArray
 var mine = new MyArray(); //创建MyArray的实例
 mine.push(1,2,3); //创建后的实例对象完全继承了Array的属性和方法
 console.log(mine.length)  //3
 mine instanceof Array; //true
 

 function P() {}
 var p = new P();
 console.log(p.constructor === P); //true
 console.log(p.constructor === P.prototype.constructor)  //true
 p.hasOwnProperty("constructor")  //false

 function Constr() {}
 var x = new Constr();

 var y = new x.constructor();
 y instanceof Constr // true

 Constr.prototype.createCopy = function() {
     return new this.constructor();
 };
 var b = x.createCopy();
 

 function Person(name) {
     this.name = name;
 }

 Person.prototype.constructor === Person // true
 //将Person.prototype对象进行重新赋值但是未指定constructor属性,则对象constructor默认指向Object
 Person.prototype = {
     method: function () {}
 };

 Person.prototype.constructor === Person // false
 Person.prototype.constructor === Object // true
        

 //利用instanceof运算符,还可以巧妙地解决,调用构造函数时,忘了加new命令的问题。
 function Person(name,age) {
     if(this instanceof Person) {
         this.name = name;
         this.age = age;
     }else {
         return new Person(name,age);
     }
 }
        

 function Father(name,age,height,weight) {
     this.name = name;
     this.age = age;
     this.height = height;
     this.weight = weight;
 }
 function Son(name,age,height,weight) {
 	 //通过call调用Father的this可为Son生成相同属性
     Father.call(this,"huzhixin",19,170,130);
 }
 var father = new Father();
 var son = new Son()
 

 function Super(){};
 Super.prototype.name = "abc";
 Super.prototype.age = 20;
 function Sub(){}
 //利用Object.create()方法将Super.prototype对象设置为Sub的原型对象,从而继承Super的属性和方法
 Sub.prototype = Object.create(Super.prototype);
 //将Sub的constructor设置为Sub
 Sub.prototype.constructor = Sub;
 var sub = new Sub();
 

 function M1(){
     this.hello = "hello";
 }
 function M2(){
     this.world = "world";
 }
 function Mine(){
 	 //调用call同时继承M1和M2的属性
     M1.call(this);
     M2.call(this);
 }
 var mine = new Mine();
 //将M1.prototype设置为Mine的原型对象
 Mine.prototype = Object.create(M1.prototype);
 //合并Mine和M2的prototype
 Object.assign(Mine.prototype,M2.prototype);
 Mine.prototype.constructor = Mine;
 console.log(mine);
 console.log(Mine.prototype.constructor)
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值