模块模式和这个

时间:2015-04-09 20:03:50

标签: javascript

我正在使用我的JavaScript“类”的模块模式。声明我正在返回的类的var self outisde然后在类构造函数中将其设置为this是否有任何明显的缺点,以便我不必担心上下文切换时不想要它。在这个小例子中,它可能是不必要的,这只是一个例子。

示例:

    var Seat = (function() {
      var self = null;
      function Seat(startX, startY, inputSeatNumber, inputTableNumber) {
        self = this;
        self.radius = 10;
        self.x = startX; self.y = startY;
        self.seatNumber = inputSeatNumber;
        self.tableNumber = inputTableNumber;
      }

      Seat.prototype.moveTo = function(newX, newY) {
        if(newX >= 0 && newY >= 0) {
          self.x = newX; self.y = newY;
        }
      };

      return Seat;
    })();

编辑:添加了示例

var SeatingChartView = (function() {
  function SeatingChartView(canvas_id, seatingChartController, seatForm) {
    this.stage = new createjs.Stage(canvas_id);
    this.controller = seatingChartController;
    this.seatForm = seatForm;

    this.disableRightClick(canvas_id);
  }

  SeatingChartView.prototype.render = function() {
    this.stage.update();
  }

  SeatingChartView.prototype.addSeat = function(newSeat) {
    var newCircle = new createjs.Shape();
    newCircle.graphics.beginFill("black").drawCircle(0, 0, 10);
    newCircle.x = newSeat.x;
    newCircle.y = newSeat.y;
    newCircle.seat = newSeat;
    newCircle.on('click', function(event) {
      if(event.nativeEvent.button == 2) {
        this.seatForm.open(event.currentTarget.seat);
      }
    });
    newCircle.on('pressmove', this.controller.moveSeat)
    this.stage.addChild(newCircle);
  }

  SeatingChartView.prototype.removeSeat = function(seat) {
    this.stage.children.forEach(function(child) {
      if(child.seat === seat) {
        this.stage.removeChild(child);
      }
    });
  }

  SeatingChartView.prototype.setBackground = function(imageLocation) {
    this.background = new createjs.Bitmap(imageLocation);
    window.setTimeout(function() {
      this.stage.canvas.width = this.background.image.width;
      this.stage.canvas.height = this.background.image.height;
      this.stage.addChild(this.background);
      this.stage.update();
    }.bind(this), 500);
  }

  SeatingChartView.prototype.disableRightClick = function(canvas_id) {
    $(function() {
      $('#' + canvas_id).bind('contextmenu', function(e) {
        return false;
      });
    });
  }

return SeatingChartView;
})();

4 个答案:

答案 0 :(得分:3)

在这种情况下,Seat的每个新实例都将共享最新的Self对象,因为它是在构造函数中设置的。你应该避免这样做。

答案 1 :(得分:3)

更实际的演示示例可能是这样的,您希望确保this是类的实例。

function Foo() {
    var _this = this;

    _this.someItem = {};

    _this.go = function() {
        doSomethingElse(function(result) {
            _this.someItem.something = result; // _this and this are different
        });
    };
};

function doSomethingElse(callback) {
    callback('asdf');
}

var foo = new Foo();
foo.go();

对于使用该模式的示例,您可以在每个方法中定义_this,如果它有任何好处(这个不会,但更复杂的例子可能):

Seat.prototype.moveTo = function(newX, newY) {
    var _this = this;
    if(newX >= 0 && newY >= 0) {
        _this.x = newX; _this.y = newY;
    }
};

答案 2 :(得分:1)

是的,通过这种方式,Seat的所有实例将具有相同的this,从而导致各地出现问题。只需删除var self,然后在您使用this的所有位置使用self。在你给出的代码中,没有必要丢失对this的引用。

(@添加示例)现在您的问题更有意义了。

您不必一次尝试为所有方法处理此问题,而是必须在使用具有不同this的函数的每个点处理它(任何不在原型或实例)。

如果您在回调中不需要this,我只需使用.bind使实例this可用。但请注意,某些(非常)旧版本的IE不支持.bind,因此您需要使用polyfil才能使用它,或者将this存储在var中。

  SeatingChartView.prototype.addSeat = function(newSeat) {
    var newCircle = new createjs.Shape();
    newCircle.graphics.beginFill("black").drawCircle(0, 0, 10);
    newCircle.x = newSeat.x;
    newCircle.y = newSeat.y;
    newCircle.seat = newSeat;
    newCircle.on('click', function(event) {
      if(event.nativeEvent.button == 2) {
        this.seatForm.open(event.currentTarget.seat);
      }
    }.bind(this)); // modified here, added `.bind(this)`
    newCircle.on('pressmove', this.controller.moveSeat)
    this.stage.addChild(newCircle);
  }

答案 3 :(得分:1)

这完全否定了"分类"的目的。但在JS中,它被称为原型设计。

主要是你希望基础原型被复制"在创建新实例时。在扩展时,应该保护基础原型免受变化。

假设您已完成所做的工作,Seat的所有实例都将具有相同的属性。更糟糕的是,在制作新的"副本时,#34; Seat的所有其他先前创建的副本将更改其值。

由于您希望this维持对Seat的引用,我建议您使用以下模式:

var Base = {
    init: function(arg) {
        this.name = arg;
    },
    getName: function() {
        return this.name;
    }
}
Base.init('foo');
Base.getName(); // returns 'foo'

您转换的代码:

var Seat = {
    init: function(startX, startY, inputSeatNumber, inputTableNumber) {
        this.radius = 10;
        this.x = startX; 
        this.y = startY;
        this.seatNumber = inputSeatNumber;
        this.tableNumber = inputTableNumber;
    },
    moveTo: function(newX, newY) {
        if (newX >= 0 && newY >= 0) {
            this.x = newX; this.y = newY;
        }
    },
    setBackground: function(imageLocation) {
        var self = this;
        this.background = new createjs.Bitmap(imageLocation);
        setTimeout(function() {
            self.stage.canvas.width = self.background.image.width;
            self.stage.canvas.height = self.background.image.height;
            self.stage.addChild(self.background);
            self.stage.update();
        }, 500);
    }
}

扩展原型:

var vipSeat = Object.create(Seat);
vipSeat.init( //your init values )

你也不能创建一个init方法,只需使用Object.create的第二个参数来为原型赋值初始值:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Example:_Using_propertiesObject_argument_with_Object.create

相关问题