美文网首页
js面向对象的constructor与instanceof

js面向对象的constructor与instanceof

作者: 尤樊容 | 来源:发表于2016-12-30 13:14 被阅读73次

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

    <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>
    

    相关文章

      网友评论

          本文标题:js面向对象的constructor与instanceof

          本文链接:https://www.haomeiwen.com/subject/hofpvttx.html