如何去掉局部函数中的 `this` 关键字?

How can I get rid of the `this` keyword in local functions?

我正在编写一个小型 JavaScript 游戏框架并且经常使用对象的属性,例如

this.depth = this.y;

但是这些 this 很烦人@_@。有没有办法只写...

depth = y;

…不影响全局对象?

我的实例是通过两个工厂函数创建的,它们列出了有限的预定义变量列表,因此它们都有 depthy 等。函数通过 .apply() 方法,尽管它可能会全部更改。

我需要省略 this 关键字的原因是该框架不仅是为我设计的,也是为其他人设计的。我不需要删除框架本身中的 this,但是 this 关键字会在基于此库编写应用程序时占用大量时间。到目前为止,我知道的唯一解决方案是制作 'private' 变量,但这给以前没有使用过 JavaScript 的人带来了一些不便,并且从 obj2 操作 obj1 会导致使用 [= 创建大量匿名函数20=] – 更地狱。所以,如我所见,JavaScript.

没有万灵药

构造函数:

/*...*/
'Copy' : function (type) {
  var obj = {
    'x':0,
    'y':0,
    'xprev':0,
    'yprev':0,
    /*...*/
  };
  return obj;
},
'make' : function (type,x,y) {
  obj = ct.types.Copy(type);
  obj.x = obj.xprev = obj.xstart = x;
  obj.y = obj.yprev = obj.ystart = y;

  /*...*/

  ct.stack.push(obj);
}
/*...*/

如果没有看到任何代码,你的问题很难回答,但总的来说,基于工厂和闭包的 "modern" JavaScript OOP 比旧 "wannabe Java" 风格与 new's 和 this's.

旧样式:

function Something() {
   this.depth = 0;
}
Something.prototype.incDepth = function() {
   this.depth++;
}
foo = new Something()

新款式:

function Something() {
   var depth = 0;
   return {
      incDepth: function() {
         depth++;
      }
   }
}
foo = Something()