JavaScript的对象原型和继承

对象的原型和继承问题

JavaScript 对象可以从对象的原型(prototype)继承属性和方法,任何一个对象(除了Object.prototype的原型是null)具有原型,也可以作为其他对象的原型,称为原型链

  1. Object.getPrototypeOf(object)可以返回参数对象的原型,顺着原型,原型的原型一级一级找,找不到该属性的话返回undefined。

  2. 为什么?

     var m2array=function(){};
     var m1array=function(){};
     m2array.prototype=m1array;
     var s = new m2array();
     s instanceof m1array() // false

constructor属性

  1. prototype对象有一个constructor属性,默认指向prototype对象所在的构造函数。prototype是在构造函数m中的,所以prototype.constructor指向prototype所在的构造函数m,实例m1是没有constructor属性的,顺着原型链找。
     var m=function(){};
     var m1=new m()
     m.prototype.constructor===m //true
     m1.constructor===m.prototype.constructor //true
  1. 可以判断实例是由哪个构造函数构造的;也可以直接instance.constructor.name知道构造函数的名字。
     var m=function(){};
     var m1=new m()
     m1.constructor===m //true
     m1.constructor===Array //false

3.直接通过实例来调用构造函数来构造新的实例

     var m=function(){};
     var m1=new m()
     var m2 = new m1.constructor();
     m2 instanceof m //true

instanceof

1.instanceof 检查左侧是否在右侧的原型链上,除了null,所有对象的instanceof Object都是true,只适用于对象,不适用其他原始数据类型

     var m=function(){};
     var m1 = new m();
     m1 instanceof m //true
     //等价于
     m.prototype.isPrototypeOf(m1) //true

2.instanceof可以解决调用构造函数忘了加new的问题

    function m(){
       if(this instanceof m){
         this.name="liming";this.age=19;
       }
       else return new m();
     }
     var s = m();
     typeof s //object

继承

function Shape() {
  this.x = 0;
  this.y = 0;
}

Shape.prototype.move = function (x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};
function Rectangle() {
  Shape.call(this); // 调用父类构造函数
  
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.method=function()
{
  return this.x+this.y;
}
var s=new Rectangle();
s.move(3,4);
s.method();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值