1

http://msdn.microsoft.com/en-us/magazine/ff696765.aspx

this website shows an example

function Circle(radius) {
  this.getRadius = function() {
    return radius;
  };
  this.setRadius = function(value) {
    if (value < 0) {
      throw new Error('radius should be of positive value');
    }
    radius = value;
  };
}

vs

Circle.prototype.getRadius = function() {
  return this._radius;
};
Circle.prototype.setRadius = function(value) {
  if (value < 0) {
    throw new Error('radius should be of positive value');
  }
  this._radius = value;
};

and on the page it states

"However, in such case, we lose the luxury of having truly private members, and have to resort to other means such as denoting privacy through convention (underscored property names). What it usually comes down to is making a choice between having truly private members or having more efficient implementation."

how does using prototype this._ losing the luxury of "truly private" members?, does prototype.this not considered as the reference to self?

4

2 回答 2

2

如果对象上的属性对原型对象上的函数中的代码可见,那么它对任何地方的代码都是可见的。

于 2013-10-07T16:20:27.290 回答
2

因为变量 this._ 是在 Circle 实例上设置的属性,因此可以从对象访问。

var c = new Circle();
c.setRadius(100);
console.log( c._radius );//100

因此,它不是一个真正的私有变量,而只是按照约定,任何以 _ 开头的东西都不应该在外部使用。

于 2013-10-07T16:24:21.173 回答