2012-03-13 4 views
2

object3.x에 대한 조회수를 얻을 수 있습니까?프로토 타입 체인에서 조회 수를 얻으시겠습니까?

첫째 - 정의 X - 질소 산화물

둘째 - - 오브젝트 4의 프로토 타입 객체에 보면 -> object2 - 질소 산화물

셋째 - object2의 프로토 타입 객체에 보면 -> 객체 1의 소유 재산 조사 - 예

object1 = {x:1}; 
object2 = Object.create(object1); 
object2.y = 2; 
object3 = Object.create(object2); 
object3.z = 3; 

object1.x; // lookup count = 1 
object2.x; // lookup count = 2 
object3.x; // lookup count = 3 
당신은 그 목적 함수를 만들 수

답변

3

...

function prop_depth(obj, p) { 
    var count = 1; 

    while(obj && !obj.hasOwnProperty(p)) { 
     obj = Object.getPrototypeOf(obj); 
     count++; 
    } 
    return obj ? count : -1; 
} 

prop_depth(object1,'x'); // lookup count = 1 
prop_depth(object2,'x'); // lookup count = 2 
prop_depth(object3,'x'); // lookup count = 3 
+1

'VAR 수 0,' 'while (obj &&! obj.hasOwnProperty (p) && ++ count) obj = Object.getPrototypeOf (obj); ' – qwertymk

+0

@qwertymk : 그래, 조금 더 멋지네. –