Javascript class 方法与原型 属性

Javascript class method vs prototype property

for-in example image

http://jsbin.com/mosedibera/edit?js,console

function Point(x, y) {
  this.x = x
  this.y = y
}

Point.prototype.point = function() {
  console.log('point')
}

var point = new Point(1, 2)
for (var x in point) {
  console.log(x)  // x y point
}
console.log(point)

class ClassPoint {
  constructor(x, y) {
    this.x = x
    this.y = y
  }
  point() {
    console.log('class point')
  }
}
var classPoint = new ClassPoint(1, 2)
for (var y in classPoint) {
  console.log(y) // x y (without point)
}
console.log(classPoint)

如图所示,我很好奇ES2015 class和prototype的区别。 for-in的结果是不同的。 (虽然使用 Object.hasOwnProperty() 可以避免这个问题)

有谁知道造成 for-in 结果的原因吗?

非常感谢!

for-in 的区别是因为 class 语法自动使方法 不可枚举 ,而当您这样做时:

Point.prototype.point = function() {
  console.log('point')
}

...在用作该构造函数创建的对象原型的对象上创建一个 enumerable 属性。

您可以通过 Object.defineProperty:

做与 class 相同的事情
Object.defineProperty(Point.prototype, "point", {
    value: function() {
        console.log('point')
    },
    writable: true
});

这会创建一个不可枚举的 属性 而不是可枚举的 属性(因为我们没有包含 enumerable: true 而默认值为 false;我们也没有包含 configurable: true 所以 属性 是不可配置的,这也是 class 对方法所做的)。

实例:

function Point(x, y) {
  this.x = x
  this.y = y
}

Object.defineProperty(Point.prototype, "point", {
    value: function() {
        console.log('point')
    },
    writable: true,
    configurable: true
});

var point = new Point(1, 2)
for (var x in point) {
  console.log(x)  // x y point
}
console.log(point)

class ClassPoint {
  constructor(x, y) {
    this.x = x
    this.y = y
  }
  point() {
    console.log('class point')
  }
}
var classPoint = new ClassPoint(1, 2)
for (var y in classPoint) {
  console.log(y) // x y (without point)
}
console.log(classPoint)


还有其他与 super 相关的细微差异,但这与您的 for-in 问题无关,并且由于您没有在该代码中使用 super,因此它们不会反正我不参与了。