1

好的,我没有得到这个。

var customer = new Object;
customer._customerID = 0;
Object.defineProperty(customer, "customerID", {
    get: function() {
    if (_customerID > -1) {
        return this._customerID;
    } else {
        throw new Error("No valid customer ID is avaliable");
    }
    },
   set: function(id) {
    if(isNaN(id) || id %1 !== 0 || id < 0) {
    throw new Error("Custom ID must have a non-negative integer");
    }
    this._customerID = id;
}
});

这段代码有什么意义?当我使用

customer._customerID = 20;
console.log (customer.customerID);

我收到错误 _customerID 未定义。我不明白这个配偶要去做什么。我对 javaScript 有点陌生,不要苛刻-)

4

1 回答 1

2

在你使用全局_customerID变量的 getter 中,你的 get 函数应该是:

function() {
  if (this._customerID > -1) {
    return this._customerID;
  } else {
    throw new Error("No valid customer ID is available");
  }
}
于 2013-11-07T18:11:51.210 回答