2010-04-08 11 views
59
function Shape() { 
    this.name = "Generic"; 
    this.draw = function() { 
     return "Drawing " + this.name + " Shape"; 
    }; 
} 

function welcomeMessage() 
{ 
    var shape1 = new Shape(); 
    //alert(shape1.draw()); 
    alert(shape1.hasOwnProperty(name)); //this is returning false 
} 

.welcomeMessage 이벤트는 body.onload 이벤트에서 호출됩니다.자바 스크립트의 hasOwnProperty

shape1.hasOwnProperty(name)이 true를 반환하지만 false가 반환 될 것으로 예상했습니다.

올바른 동작은 무엇입니까?

+4

그것이 문자열이 필요, 반대로 너무 ' "이름이"'에'name' [자바 스크립트의 –

+0

가능한 중복 속성이 hasOwnProperty에 포함되는 것 ?] (http://stackoverflow.com/questions/9396569/javascript-what-is-property-in-hasownproperty) –

답변

129

hasOwnProperty은 문자열 인수를 취하는 일반적인 Javascript 함수입니다.

shape1.hasOwnProperty(name)을 호출하면 alert(name)을 작성한 경우와 같이 name 변수 (존재하지 않음)의 값을 전달하게됩니다.

shape1.hasOwnProperty("name")과 같이 name이 포함 된 문자열로 hasOwnProperty을 호출해야합니다.

3

이 시도 :

 
function welcomeMessage() 
{ 
    var shape1 = new Shape(); 
    //alert(shape1.draw()); 
    alert(shape1.hasOwnProperty("name")); 
} 

자바 스크립트에 반사와 협력, 구성원 개체는 항상 문자열로 이름으로에 대해 참조한다. 예를 들어 제가

것이다

for(i in obj) { ... }

루프 반복자은 속성 이름의 문자열 값을 잡아.

 
for(i in obj) { 
    alert("The value of obj." + i + " = " + obj[i]); 
} 
17

hasOwnProperty 문자열로 속성 이름을 예상하고,이

+0

"문자열"부분이 누락되었습니다. 감사. –

1

shape1.hasOwnProperty("name") 내가위한 오픈 소스 구성 요소를 작성 될 수 있도록 : 코드에서이 같은 배열 연산자를 사용하여 속성을 해결해야한다는 사용 그게 object-hasOwnProperty입니다.

예 :

hasOwnProperty({foo: 'bar'}, 'foo') // => true 
hasOwnProperty({foo: 'bar'}, 'bar') // => false 

의 Src 코드 :

function hasOwnProperty(obj: {}, prop: string|number): boolean { 
    return Object.prototype.hasOwnProperty.call(obj, prop); 
}; 
+1

이것은 _why_에 응답하지 않습니다. Object.hasOwnProperty()의 내부 동작에 대해 좀 더 자세히 설명해주십시오. –