instanceof() VS isPrototypeOf() hasOwnProperty() VS propertyIsEnumerable()
이 몇 가지 방법 은 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 }
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.