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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值