私有属性的Javascript动态getter/setter

Wil*_*ilk 5 javascript private dynamic getter-setter prototype-programming

我想动态地创建getter/setter方法来检索私有属性.

这就是我做的.

首先,我上课了:

function winClass (posX, posY, w, h) {
  var x = posX || 0;
  var y = posY || 0;
  var width = w || 0;
  var height = h || 0;
}
Run Code Online (Sandbox Code Playgroud)

然后我用getter/setter方法扩展了winClass,如下所示:

winClass.prototype.getX = function () {
  return x;
}

winClass.prototype.setX = function (val) {
  x = val;
}
Run Code Online (Sandbox Code Playgroud)

然后我测试了:

var win1 = new winClass (10, 10, 100, 100);
document.write (win1.getX ());
Run Code Online (Sandbox Code Playgroud)

但是当我尝试设置'getX'方法时出现以下错误:'x未定义'.这是有道理的,因为'x'不在winClass范围内,但因此我不知道如何为私有变量设置动态getter/setter方法.

有任何想法吗?

jfr*_*d00 13

getter/setter必须在可以看到私有变量的范围内,并且唯一可以看到这些变量的范围是构造函数的内部.这就是为什么这些变量实际上是私有的.因此,要为它们制作setter/getter,您必须将函数放在可以看到它们的范围内.这将有效:

function winClass (posX, posY, w, h) {
  var x = posX || 0;
  var y = posY || 0;
  var width = w || 0;
  var height = h || 0;

  this.getX = function() {return(x);}
  this.setX = function(newX) {x = newX;}
}

var win1 = new winClass (10, 10, 100, 100);
alert(win1.getX());   // alerts 10
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它的工作:http://jsfiddle.net/jfriend00/hYps2/.

如果你想要私有的通用getter/setter,你可以这样做:

function winClass (posX, posY, w, h) {
  var privates = {};
  privates.x = posX || 0;
  privates.y = posY || 0;
  privates.width = w || 0;
  privates.height = h || 0;

  this.get = function(item) {return(privates[item]);}
  this.set = function(item, val) {privates[item] = val;}
}

var win2 = new winClass(10,10,100,100);
alert(win2.get("x"));    // alerts 10
Run Code Online (Sandbox Code Playgroud)

并且,如果你想破解这些变量的私有性,这对我来说没有意义(因为你可能会把它们变成标准的实例变量),你可以这样做:

function winClass (posX, posY, w, h) {
  var privates = {};
  privates.x = posX || 0;
  privates.y = posY || 0;
  privates.width = w || 0;
  privates.height = h || 0;

  this.getPrivates = function() {return(privates);}
}

winClass.prototype.getX = function() {
    return(this.getPrivates().x);
}

winClass.prototype.setX = function(newX) {
    this.getPrivates().x = newX;
}
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/jfriend00/EKHFh/.

当然,这会破坏变量的私有性,因此实际上没有任何意义,因为使它们成为常规实例变量会更容易并具有相同的访问控制.

并且,为了完整性,这里是正常的实例变量方法,它可以自由地为原型添加访问器方法,但变量不是私有的.

function winClass (posX, posY, w, h) {
  this.x = posX || 0;
  this.y = posY || 0;
  this.width = w || 0;
  this.height = h || 0;
}

winClass.prototype.getX = function() {
    return(this.x);
}

winClass.prototype.setX = function(newX) {
    this.x = newX;
}
Run Code Online (Sandbox Code Playgroud)

  • @Ed治愈 - 你需要给予原型继承更多信用.Javascript't Prototype的概念来自[自我语言](http://en.wikipedia.org/wiki/Self_%28programming_language%29)和(除了语法之外)根本不是软糖. (2认同)