你有几个术语有问题。
- 您没有“查询构造函数对象”。您可以枚举实际对象的属性,但不能枚举构造函数。
- 您在代码示例中创建属性的方式不是使用对象的
prototype,因此如果您要迭代对象的原型,您将看不到radius 属性。
假设您真正想说的是:“如何迭代我的 Circle 对象实例的属性?”,答案将是这样的:
function Circle()
{
this.radius = 3;
this.border = 1;
this.color = "red";
}
var obj = new Circle();
for (var i in obj) {
// hasOwnProperty makes sure we get properties only of Circle,
// not of ancestors like Object
if (obj.hasOwnProperty(i)) {
// i will be properties of obj on each iteration
console.log(i); // radius, border, color
}
}
对象的原型是另一回事。您可以将其视为对象的每个新实例都会自动继承的结构。你可以像这样使用原型:
function Circle(r)
{
this.radius = r;
this.border = 1;
this.color = "red";
}
Circle.prototype.calcArea = function() {
return(Math.PI * this.radius * this.radius);
}
Circle.prototype.calcCircumference = function() {
return(Math.PI * this.radius * 2);
}
这将自动为每个 Circle 实例提供两个方法 calcArea 和 calcCircumference。
var cir = new Circle(4);
console.log(cir.calcArea()); // 54.624
您还可以将方法添加到您没有代码的预先存在的对象的原型,例如 Array(尽管这样做时您必须小心)。例如:
Array.prototype.isSorted = function() {
for (var i = 1; i < this.length; i++) {
if (this[i] < this[i-1]) {
return(false);
}
}
return(true);
}
var x = [1,3,6,8];
var y = [1,3,8,6];
console.log(x.isSorted()); // true
console.log(y.isSorted()); // false