如何在javascript中为策略设计模式创建属性?

时间:2016-02-10 21:17:06

标签: javascript design-patterns google-chrome-extension properties strategy-pattern

https://gist.github.com/Integralist/5736427

上面链接的这部分代码给了我麻烦。 背景:在“使用严格”条件下在镀铬扩展程序中运行

var Greeter = function(strategy) {
  this.strategy = strategy;  
};

// Greeter provides a greet function that is going to
// greet people using the Strategy passed to the constructor.
Greeter.prototype.greet = function() {
  return this.strategy();
};

我想我需要创建属性'greet'但不知道如何。

我不断收到错误,说“无法设置属性'问候'未定义”

如何创建属性greet并使代码生效?

谢谢!

更新这是我的代码在我的扩展程序中的方式

var MessageHandling = new function(strategy) {
    this.strategy = strategy;
};
MessageHandling.prototype.greet = function () {
    return this.strategy();
};
//Later
var openMessage = new MessageHandling(openMessageAnimationStrategy);
openMessage.greet();

1 个答案:

答案 0 :(得分:0)

问题出在构造函数定义MessageHandling中。您需要删除new关键字,因为这里没有意义。
而不是这段代码:

var MessageHandling = new function(strategy) {
    this.strategy = strategy;
};

使用它:

var MessageHandling = function(strategy) {
    this.strategy = strategy;
};

new operator用于从构造函数创建对象实例。您不需要将它用于构造函数定义。