나는 몇 가지 코드가 객체의 프로토 타입의 속성을 반복합니다. 나는 for 루프가 을 확인하지 않았기 때문에 obj
의 프로토 타입 (즉, bar
)의 속성을 반복 할 것으로 예상했습니다. 내가 여기서 무엇을 놓치고 있니? 프로토 타입의 모든 속성을 반복하는 관용적 인 방법이 있습니까?어떻게
Chrome 및 IE10에서이를 테스트했습니다.
미리 감사드립니다.
나는 몇 가지 코드가 객체의 프로토 타입의 속성을 반복합니다. 나는 for 루프가 을 확인하지 않았기 때문에 obj
의 프로토 타입 (즉, bar
)의 속성을 반복 할 것으로 예상했습니다. 내가 여기서 무엇을 놓치고 있니? 프로토 타입의 모든 속성을 반복하는 관용적 인 방법이 있습니까?어떻게
Chrome 및 IE10에서이를 테스트했습니다.
미리 감사드립니다.
생성자의 속성을 반복하고 있으므로 인스턴스를 만들어야합니다. 인스턴스 생성자의 prototype
속성에서 상속하는 것입니다 : 당신도 객체 인스턴스화하기 전에 모든 속성을 정의하여 상속 계층 구조를 유지하려는 경우, 당신은 아래 방법을 따라 할 수
var Ctor = function() { }; // constructor function
Ctor.prototype.bar = 'bar';
var obj = new Ctor(); // instantiation
// adds own property to instance
obj.foo = 'foo';
// logs foo and bar
for (var prop in obj) {
console.log(prop);
}
아하! 고맙습니다. – gwg
. 이 방법은 프로토 타입 계층 구조 체인을 인쇄합니다.
참고 :이 방법에서는 처음에는 생성자를 만들지 않아도됩니다.
function myself() {
this.g = "";
this.h = [];
this.i = {};
myself.prototype = new parent();
myself.prototype.constructor = myself;
}
function parent() {
this.d = "";
this.e = [];
this.f = {};
parent.prototype = new grandParent();
parent.prototype.constructor = parent;
}
function grandParent() {
this.a = "";
this.b = [];
this.c = {};
}
var data = new myself();
var jsonData = {};
do {
for(var key in data) {
if(data.hasOwnProperty(key) && data.propertyIsEnumerable(key)) {
jsonData[key] = data[key];
}
}
data = Object.getPrototypeOf(data).constructor.prototype;
Object.defineProperties(data, {
'constructor': {
enumerable: false
}
});
} while (data.constructor.name !== "grandParent")
console.log(jsonData);
프로토 타입에 속성을 추가하면 해당 속성이 개체 자체가 아닌 해당 개체의 인스턴스에서 사용할 수있게됩니다. –