>  기사  >  웹 프론트엔드  >  Javascript 연구 노트 - 객체(3): hasOwnProperty_Basic 지식

Javascript 연구 노트 - 객체(3): hasOwnProperty_Basic 지식

WBOY
WBOY원래의
2016-05-16 16:43:221094검색
// Poisoning Object.prototype
Object.prototype.bar = 1;
var foo = {goo: undefined};

foo.bar; // 1
'bar' in foo; // true

foo.hasOwnProperty('bar'); // false
foo.hasOwnProperty('goo'); // true

여기서는 hasOwnProperty만이 정답을 줄 수 있는데, 이는 객체의 속성을 순회할 때 매우 필요합니다. Javascript에는 속성이 객체 자체에 정의되어 있는지 또는 프로토타입 체인에서 상속되는지 여부를 알 수 있는 다른 방법이 없습니다.

hasOwnProperty를 속성으로

Javascript에서는 hasOwnProperty를 민감한 단어로 만들지 않습니다. 즉, hasOwnProperty라는 속성을 가질 수 있습니다. 현재로서는 더 이상 자체 hasOwnProperty 메소드를 사용하여 속성을 판단할 수 없으므로 외부 hasOwnProperty 메소드를 사용하여 판단해야 합니다.

var foo = {
 hasOwnProperty: function() {
 return false;
 },
 bar: 'Here be dragons'
};

foo.hasOwnProperty('bar'); // always returns false

// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true

// It's also possible to use hasOwnProperty from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

요약

객체 속성의 존재 여부를 확인할 때 신뢰할 수 있는 유일한 방법은 hasOwnProperty입니다. 또한 for in 루프를 사용하여 객체를 탐색할 때 hasOwnProperty를 사용하면 프로토타입 객체 확장으로 인해 발생하는 문제를 효과적으로 피할 수 있다는 점을 상기시키고 싶습니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.