2011-10-28 3 views
0

나는 더미 생성자 객체가있는 경우 :JavaScript에서 객체의 프로토 타입 속성을 반복하는 방법은 무엇입니까?

function Circle() 
{ 
    this.radius = 3; 
} 

이 개체의 인스턴스는 하나의 "반경"속성을 것입니다. a) 생성자 객체에 속성의 수를 쿼리하려면 어떻게해야합니까?

b) 가지고있는 속성의 수에 대해 Circle.prototype을 어떻게 쿼리합니까? 아무것도

+3

프로토 타입이 아닙니다. – SLaks

답변

1

당신이 잘못 몇 가지 용어 일들이에게 반환하지 않습니다 console.log(Object.getOwnPropertyNames(Circle.prototype)) 같은 것을 시도.

  1. "생성자 개체를 쿼리하지 않습니다." 실제 개체의 속성을 열거 할 수 있지만 생성자 함수는 열거 할 수 없습니다.
  2. 코드 예제에서 속성을 만드는 방법에서는 개체의 prototype을 사용하지 않으므로 개체의 프로토 타입을 반복 할 경우 radius 속성이 표시되지 않습니다.

당신이 정말로 말을 무슨 뜻인지 가정입니다 : "나는 내 서클 개체의 인스턴스의 속성을 반복합니까?"대답은 다음과 같이 될 것이다 :

function Circle() 
{ 
    this.radius = 3; 
    this.border = 1; 
    this.color = "red"; 
} 

var obj = new Circle(); 
for (var i in obj) { 
    // hasOwnProperty makes sure we get properties only of Circle, 
    // not of ancestors like Object 
    if (obj.hasOwnProperty(i)) { 
     // i will be properties of obj on each iteration 
     console.log(i);  // radius, border, color 
    } 
} 

의 프로토 타입 사물은 다른 것입니다. 객체의 모든 새로운 인스턴스가 자동으로 상속받는 구조처럼 생각할 수 있습니다. 이 같은 프로토 타입을 사용할 수

function Circle(r) 
{ 
    this.radius = r; 
    this.border = 1; 
    this.color = "red"; 
} 

Circle.prototype.calcArea = function() { 
    return(Math.PI * this.radius * this.radius); 
} 

Circle.prototype.calcCircumference = function() { 
    return(Math.PI * this.radius * 2); 
} 

이 자동으로 서클의 모든 인스턴스, 두 가지 방법 calcArea 및 calcCircumference을 줄 것이다.

var cir = new Circle(4); 
console.log(cir.calcArea()); // 54.624 

또한 (당신이이 일을 할 때 조심해야하지만) 당신이 배열 등의 코드가없는 기존 객체의 프로토 타입 방법을 추가 할 수 있습니다. 예 :

Array.prototype.isSorted = function() { 
    for (var i = 1; i < this.length; i++) { 
     if (this[i] < this[i-1]) { 
      return(false); 
     } 
    } 
    return(true); 
} 

var x = [1,3,6,8]; 
var y = [1,3,8,6]; 

console.log(x.isSorted()); // true 
console.log(y.isSorted()); // false 
+0

@ jfriend00 내가 혼란스러워하는 부분은 생성자 함수와 객체 프로토 타입 사이의 차이점이 무엇인지 생각해보십시오. 'function Circle()' '{' ' this.radius = 3; '}' 'var cir = new Circle(); ' 'console.log (cir.prototype); // undefined를 반환합니다. ' – user1019031

+0

실제 프로토 타입의 일부 샘플 사용을 보여주기 위해 필자의 대답에 더 많은 것을 추가했습니다. – jfriend00

+0

@ user1019031 : 수락 된 답변을 기억하십시오. – Alex

1

hasOwnProperty

var cir = new Circle(); 
var j = 0; 
for(var i in cir) { 
    if (cir.hasOwnProperty(i)) { 
     j++; 
    } 
} 

j == 1; // true 
관련 문제