instanceof() VS isPrototypeOf() hasOwnProperty() VS propertyIsEnumerable()

다음으로 이동:http://www.2cto.com/kf/201404/291977.html
이 몇 가지 방법 은 js 의 고급 프로 그래 밍 에 있다.
에서 자주 사용 되 는데 초보 자 에 게 그들 이 어떤 차이 가 있 는 지 모 를 수도 있 습 니 다. 저 는 제 경험 을 정리 하여 여러분 께 참고 하도록 하 겠 습 니 다.
우선, 대상 을 정의 합 니 다.
 1  function Parent() {this.name = "wenbo";
 2  Parent.prototype.alertP = function() {
 3      alert("Parent");
 4  }
 5
 6  function Child() {this.age = 23;}
 7  Child.prototype.alertC = function() {
 8      alert("Child");
 9  }
10 
11  function F() {}
12  F.prototype = Parent.prototype;
13
14  //   Child         F    
15  Child.prototype = new F();
16  Child.prototype.constructor = Child;
17
18  //     Child   
19  var child = new Child();

1、instanceof()   vs   isPrototypeOf():
instanceof: 이 대상 이 다른 대상 인지 아 닌 지 를 판단 하 는 실례 입 니 다.
 
1  console.log(child instanceof  Parent); //true  
2  console.log(child instanceof  Child); //true</span> </span>

isPrototypeOf: 하나의 대상 (또는 함수 또는 클래스) 이 인 스 턴 스 의 원형 인지 판단 합 니 다.
 
1 Parent.prototype.isPrototypeOf(child);//true
2 Child.prototype.isPrototypeOf(child);//true

2、hasOwnProperty()   vs  propertyIsEnumerable(): 
hasOwnProperty: 대상 이 특정한 속성 이 있 는 지 판단 합 니 다. (대상 의 원형 이 아 닌 대상 의 속성 을 주의 하 십시오) 문자열 로 이 속성 을 지정 해 야 합 니 다.
1 Parent.hasOwnProperty("name");//true
2 Child.hasOwnProperty("age");//true
3 Parent.hasOwnProperty("alertP");//false
4 Child.hasOwnProperty("alertC");//false

property IsEnumerable: 주어진 속성 이 for... in 문 구 를 사용 할 수 있 는 지 판단 합 니 다.for... in 매 거 진 은 프로 토 타 입 체인 의 속성 을 포함 하기 때문에 property IsEnumerable 은 프로 토 타 입 방법 에 작용 할 때 항상 false 로 돌아 갑 니 다. for.. in 은 대상 자체 의 속성 과 프로 토 타 입 상의 속성 을 매 거 진 할 수 있 고 property IsEnumerable 은 자체 의 속성 을 매 거 진 할 수 있 는 지 여 부 를 판단 할 수 있 습 니 다.그 밖 에 미리 정 의 된 속성 은 열거 할 수 있 는 것 이 아니 라 사용자 가 정의 한 속성 은 항상 열거 할 수 있다.그래서 대상 자체 의 속성 만 옮 겨 다 니 고 싶다 면:
 
1 for (var key in obj) {
2   if (obj.hasOwnProperty(key) {
3      //do something
4   }
5 }

좋은 웹페이지 즐겨찾기