js面向对象的constructor与instanceof

面向对象的一个简单的例子:

<script>
    /*构造函数(函数名采用大驼峰)*/
function CreatePerson(name,age){
    this.name = name;
    this.age = age;
}
CreatePerson.prototype.showName = function(){
    return this.name;
};
CreatePerson.prototype.showAge = function(){
    return this.age;
};
var p1 = new CreatePerson('aaa',12);
var p2 = new CreatePerson('bbb',18);
console.log('p1的名字:'+p1.showName());//aaa
console.log(p1.showAge === p2.showAge);//true
/*instanceof检查父级、父级的父级...,正确返回true,不正确返回false*/
console.log("instanceof检查父级、父级的父级...,正确返回true,不正确返回false");
console.log(p1 instanceof CreatePerson);//true
console.log(p1 instanceof Object);//true
console.log(CreatePerson instanceof Object);//true
/*这里有一个坑,p1不是Function的子集,但是CreatePerson是*/
console.log(p1 instanceof Function);//false
console.log(CreatePerson instanceof Function);//true
/*constructor只检查父级*/
console.log("constructor只检查父级");
console.log(p1.constructor == CreatePerson);
console.log(p1.constructor == Object);
</script>

像数组Array、Date等封装好的也有这样的问题,比如数组:

//var arr = [1,2];
 var arr=new Array(1,2);
 console.log(arr instanceof Array);//true
 console.log(Array instanceof Object);//true
 console.log(arr instanceof Object);//true

 console.log(arr instanceof Array);//true
 console.log(Array instanceof Function);//true
 console.log(arr instanceof Function);//false

继承

<script>
   function Person(name,age){
      this.name='are you die?'+name;
      this.age=age;
   };
   Person.prototype.showName=function(){
      return this.name;
   };
   Person.prototype.showAge=function(){
      return this.age;
   };
   function Worker(name,age,job){
      /*属性继承,这三种方法都可以*/
      //Person.call(this,name,age);
      //Person.apply(this,[name,age]);
      Person.apply(this,arguments);
      this.job=job;
   };
   Worker.prototype.showJob=function(){
      return this.job;
   };
   //方法继承一 
  Worker.prototype=new Person();
   /*new过以后父级指向变成了person,所以需要指定一下父级*/
   Worker.prototype.constructor=Worker;
   /*方法继承二*/
   /*for(var name in Person.prototype){
      Worker.prototype[name]=Person.prototype[name];
   }*/
   var w1=new Worker('小明','18','医生');
   //alert(w1.showJob());
   alert(w1.showAge());
   //alert(w1.constructor==Person);//false
   alert(w1.constructor==Worker);//true
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,211评论 6 13
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,272评论 0 4
  • “最怕一生碌碌无为,还安慰自己平凡可贵”
    NAMSHIN阅读 188评论 0 0
  • “所有的大人都曾经是小孩,虽然,只有少数的人记得。” 不管年纪多大,每个人心中都有一个长不大的小孩,充满了童真童趣...
    张铁钉阅读 1,104评论 4 8
  • 今天下班回来心情很低落,自己总找不到地方发泄,回到家和老公说两句话了,可是话不投机,总是打击我。让我心里还更难过。...
    僞妳鎖訫阅读 269评论 0 0