Javascript对象部分编辑

时间:2017-03-07 22:10:58

标签: javascript

我想在javascript中创建一个封闭的对象,只能使用Object.defineProperty进行编辑,而不是以正常的方式对其进行编辑...

目标是,我正在创建一个lib,用户可以在其中读取一个名为dictionary的对象,但是他们也可以编辑它!是否有任何方法可以让用户读取并由我编辑的对象?

3 个答案:

答案 0 :(得分:0)

无法保护任何物体部件。

另见: How to Create Protected Object Properties in JavaScript

答案 1 :(得分:0)

您可以使用Object.defineProperty提供一些基本保护:

var o = { a: 5 };

o._protected = {};
o._protected.a = o.a;
Object.defineProperty(o, 'a', {
  get: function() { return this._protected.a; },
  set: function(value) {
   if (value > 0 && value < 5) {
     this._protected.a = value;
   }
  configurable: false
});

这将限制此对象中属性a的更改,以便它们将通过get(读取)/ set(更新)。当然,在这种情况下,_protected对象可以被操纵,但它确实需要用户有意识地“破解”它。尝试直接更改财产a将由您控制。

在这个例子中,尝试设置o.a = 6将导致o.a没有变化(当然,如果可以的话,你可以将它设置为你的set函数中允许的最大值)。

您可以通过不提供设置功能来阻止对o.a的更改。

这对于确保属性仅获得“有效”值非常方便,而且我经常以这种方式使用它。

答案 2 :(得分:0)

我找到了!请告诉我这个解决方案有什么问题:

String replaceHalf(String input, String search) {
  String reversed = new StringBuilder(search).reverse().toString();
  StringBuilder sb = new StringBuilder(input);
  int pos = -search.length();
  while (true) {
    // Find the next occurrence...
    pos = input.indexOf(search, pos + search.length());
    if (pos == -1) break;

    // ...but ignore it, and find the next occurrence.
    pos = input.indexOf(search, pos + search.length());
    if (pos == -1) break;

    sb.replace(pos, pos + search.length(), reversed);
  }
  return sb.toString();
}
相关问题