js 대상을 위한constructor와 instanceof

2262 단어
객체에 대한 간단한 예:

    /* ( )*/
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);


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


계승

   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

좋은 웹페이지 즐겨찾기