如何避免在Javascript原型中使用“this”

时间:2014-05-25 01:18:20

标签: javascript this prototypal-inheritance

这是我的javascript对象,我想知道如何避免使用"这个"在原型中这么多次。我知道有很多关于原型内在性的理论和联系,这可能已经得到了解答,但由于我还没能完成所有目标,我认为这可能值得另一个问题。

function shape(smth) {
    this.a = smth
    this.b = 2
    this.c = 3
}

shape.prototype.doCalculus = function () {
    return this.a * this.b + this.c - (2 * (this.b + this.c) + this.a);
}

module.exports = shape

5 个答案:

答案 0 :(得分:8)

如果你想要一个对象的公共成员,它们必须从this指针引用。这就是OO在Javascript中的工作方式。别无选择。

如果在函数中有很多对同一变量的引用,可以暂时将它放在局部变量中,只是为了保存一些引用逻辑(与任何多步引用相同),但是你仍然需要初始检索使用this.varName


有一个方案在构造函数闭包中使用“私有”成员变量,并且不使用可以在某些情况下使用的原型,这允许您直接引用变量而不使用this

function shape(smth) {
    var a = smth,
        b = 2,
        c = 3;

    this.doCalculus = function() {
        return a * b + c - (2 * (b + c) + a);
    }
}

module.exports = shape

对于创建大量实例的对象类型,这可能会占用更多内存,因为方法不存储在共享原型中,而是为每个实例单独创建。有人认为,在大多数用途中,记忆消耗的差异并不重要。

答案 1 :(得分:5)

可以避免在构造函数中使用this,使用Object.create创建原型链,然后直接在结果对象上声明属性。

function Shape(smth) {
  var shape = Object.create(Shape.prototype);

  shape.a = smth;
  shape.b = 2;
  shape.c = 3;

  return shape;
}

这消除了this函数中Shape的需要,这意味着我们不再需要使用new调用它。

new Shape(1); // { a: 1, b: 2, c: 3, __proto__: Shape.prototype }
Shape(1);     // { a: 1, b: 2, c: 3, __proto__: Shape.prototype }

但是,您仍需要在原型方法中使用this来引用正确的实例。

答案 2 :(得分:2)

您可以避免this这样:

function Shape(smth) {
    return {"a": smth, "b": 2, "c": 3 };
}

但我要添加的一个警告是返回的对象似乎不能很好地使用Shape.prototype.methodname添加方法

因此,就我原来的例子而言,你需要做的是:

function Shape(smth) {
    return {"a": smth, 
            "b": 2, 
            "c": 3,
            doCalculus: function () {
                return this.a * this.b + this.c - (2 * (this.b + this.c) + this.a);
            }
    }

所以你仍然最终得到了这个,并且你已经失去了在prototype下分离方法的优势。我也试图让jslint传递我的代码,而没有勾选#34; Tolerate ... this"方框,但我得出的结论是,使用this要好得多。除Douglas Crockford之外的所有人似乎都接受它作为javascript的一个组成部分。

答案 3 :(得分:1)

如果你想避免"这个",你可以这样做:

const shape = smth => {
      let a = smth,
          b = 2,
          c = 3;
      return {
        doCalculus: () => a * b + c - (2 * (b + c) + a)
      }
    }

    console.log(shape(2).doCalculus()); // -5

答案 4 :(得分:0)

您可以使用with statement,,尽管不推荐使用它,却不能在strict mode.

中使用

function Shape(smth) {
    this.a = smth;
    this.b = 2;
    this.c = 3;
}

Shape.prototype.doCalculus = function () {
    with(this) {
        return a * b + c - (2 * (b + c) + a);
    }
};

console.log(new Shape(5).doCalculus());

相关问题