logo

자바스크립트 hasOwnProperty

이번 튜토리얼에서는 hasOwnProperty() JavaScript의 메소드. 또한 섹션에서 구현 및 사용법에 대해 알아봅니다.

소개

~ 안에 자바스크립트 , hasOwnProperty() 메서드는 객체가 언급된 프로젝트에 속하는지 여부를 확인하는 속성으로 정의됩니다. 속성이 인식된 개체에 속하는 것으로 확인되면 부울 문 기반 출력(예: true 또는 false)을 반환합니다.

통사론

 object.hasOwnProperty(propname) 

논쟁

녹음:

여기서는 기호나 문자열이 객체에 속하는지 확인하는 prop의 위치이기 때문에 기호나 문자열 이름을 전달해야 합니다. 이는 아래 제공된 방법을 사용하여 수행됩니다.

 var movie = { name: 'iron man', genre: 'super hit', } var song = { name: 'cardigan', } movie.hasOwnProperty('name'); // returns true movie.hasOwnProperty('type'); // returns false song.hasOwnProperty('name'); // returns true song.hasOwnProperty('status'); // returns false 

여기서 주목해야 할 중요한 측면 중 하나는 hasOwnProperty() 메서드가 일반적으로 상속된 속성을 무시한다는 것입니다. 즉, 객체에 상속되지 않은 속성이 있고 이름이 propname으로 지정된 경우 메서드가 true를 반환해야 함을 의미합니다. false를 반환하면 객체에 지정된 이름을 가진 속성이 없거나 proptype의 객체에서 속성을 상속했음을 의미합니다.

 // Create an object var o = new Object(); // Define a noninherited local property o.x = 3.14; o.hasOwnProperty('x'); // Returns true: x is a local property of o o.hasOwnProperty('y'); // Returns false: o doesn't have a property y o.hasOwnProperty('toString'); // Returns false: toString property is inherited hasOwnProperty() will return true even if you define the undefined or null value. let a = new Object(); a.propertyOne = null; a.hasOwnProperty('propertyOne') // output: true a.propertyTwo = undefined; a.hasOwnProperty('propertyTwo') //Output: true 

hasOwnProperty() 메서드를 사용하는 또 다른 이점은 문자열을 기본 인수로 전달하는 개념을 따라 객체를 초기화할 수 있다는 것입니다. 값이 객체에 사용 가능한 것으로 확인되면 신속하게 true로 응답해야 합니다. 그렇지 않으면 찾을 수 없으면 false를 반환합니다. 아래에 제공된 코드 조각을 사용하여 시연할 수 있습니다.

 function Car(name) { this.name = name; } Car.prototype.color = 'red'; const bmw = new Car('x1'); console.log(bmw.name); // property found on object console.log(bmw.color); // color property found on prototype console.log(bmw.hasOwnProperty('name')); // name is found on the object itself console.log(bmw.hasOwnProperty('color')); // color property is not found on the object itself 

위에 제공된 코드 조각에서 변수는 새 객체를 생성합니다. 자동차 . 이제 생성자 아래에 정의된 속성과 이름을 사용하여 Car가 시작되었다고 말할 수 있습니다. 시작 시 개체 내에서 색상이 언급되지 않을 수도 있지만 프로토타입에서는 항상 사용할 수 있습니다. 계층 . 따라서 hasOwnProperty()는 이름에 대해서는 항상 true를 반환하지만 색상에 대해서는 false를 반환합니다.

성능 측면에서 hasOwnProperty()는 루프를 통해 객체를 통과하면서 원활하게 작동합니다. 지금쯤이면 속성이 구체적으로 객체에 속한다고 말할 수 있습니다. 프로토타입과 아무런 상관관계가 없습니다. 이에 대한 데모는 아래 제공된 코드 조각을 사용하여 표시할 수 있습니다.

 // declaring a Car function function Car(name) { this.name = name; } // setting up new prop with prototype Car.prototype.color = 'red'; // creating a new Car object const BMW = new Car('x1'); // looping through every car prop including prototype as well for (let car in BMW) { car + ':', BMW[car]; } /* output: name: x1 output: color: red */ /**************************************/ /*will loop through only self properties of the object, excludes property generated through prototype method */ for (let car in BMW) { if (BMW.hasOwnProperty(car)) { console.log(car + ':', BMW[car]); } } // output: name: 

hasOwnProperty() 메서드를 사용하는 동안 hasOwnProperty라는 속성을 정의할 때 객체 렌더링이 발생하므로 쓸모 없게 될 수 있습니다. 이를 지원하려면 아래 제공된 코드 조각을 이해해 보십시오.

 var harrypotter = { hasOwnProperty: function() { return true; } }; // Outputs: true console.log(harrypotter.hasOwnProperty('ridikulus')); 

위의 코드 조각에서 harrypotter가 이미 hasOwnProperty를 갖고 있음이 분명합니다. 따라서 object.prototype.hasOwnProperty를 호출하지 않습니다. 전화를 걸 수는 있지만 결국 실패하는 경우가 발생할 수 있다고 가정합니다. 따라서 항상 통화 가능성에 유의하는 것이 좋습니다. 아래 코드 조각은 해결 방법을 보여줍니다.

 // Returns false Object.prototype.hasOwnProperty.call(harrypotter, 'ridikulus'); 

위의 코드 조각에서 harrypotter가 자체적으로 정의한 것이 분명합니다. hasOwnProperty . Object.prototype.hasOwnProperty는 절대 호출하지 않습니다. 값이 false인 경우가 발생하면 false를 반환할 가능성이 있고 모퉁이에서 작업을 수행하기가 어려워지기 때문입니다. 이 설명을 뒷받침하려면 아래에 제공된 코드 조각을 참조하세요.

 // Returns false Obje ct.prototype.hasOwnProperty.call(harrypotter, 'ridikulus'); 

hasOwnProperty와 유사하게 'in' 메소드라는 또 다른 메소드가 있습니다. 또한 객체에 키가 있는지 여부를 확인하는 데에도 사용됩니다. 그러나 hasOwnProperty와 in 메소드의 주요 차이점은 in 메소드가 상속되는 속성과 상속된 속성이 객체에 대해 특별히 생성되는 속성을 구별하는 순서를 따르지 않는다는 사실에 있다는 점에 유의하는 것이 중요합니다. 이는 아래 제공된 코드 조각을 사용하여 표시할 수 있습니다.

 var fantasyLit = { tolkien: 'The Lord of the Rings', lewis: 'The Chronicles of Narnia' }; // Outputs: true console.log('tolkien' in fantasyLit); // Outputs: false console.log('asimov' in fantasyLit); // Outputs: true console.log('constructor' in fantasyLit); 

위의 코드 조각에서 'in' 메소드는 모든 객체가 상속되는 Object.prototype의 생성자 속성을 따른다는 것이 분명합니다.

몇 가지 점을 추가하자면 두 방법 모두 단점이 있습니다. 두 가지 방법 모두 이미 선언된 속성에 대한 정보를 쉽게 제공할 수 있지만 실제 값이 포함된 속성에 대해서는 알려줄 수 없습니다.

두 메서드 모두에서 이 해결 방법을 수행하는 방법을 보여주는 다음 코드 조각을 고려하세요.

 // Puts a 'declared' property on the global object // (window in browsers) var declared; // Outputs: true console.log('declared' in window); // Outputs: true console.log(window.hasOwnProperty('declared')); // Outputs: undefined console.log(declared); var obj = { myUndefined: undefined }; // Outputs: true console.log('myUndefined' in obj); // Outputs: true console.log(obj.hasOwnProperty('myUndefined')); // Outputs: undefined console.log(obj.myUndefined); 

결론

이 튜토리얼에서는 JavaScript의 hasOwnProperty() 메소드에 대해 논의했습니다. 일반적으로 이 방법은 대부분의 개발자가 생성자와 같은 일부 특수 키와 관련된 문제를 문의하고 방지하기 위한 훌륭한 선택입니다. 속성이 있는 객체를 찾으면 기본적으로 hasOwnProperty()를 사용하는 것이 좋습니다. toString() 메소드에 대한 객체를 확인하여 호출하려는 함수가 있는 경우 in을 사용해야 합니다.