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

How to create properties for a Strategy Design Pattern in javascript?

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

上面 link 中的这部分代码给我带来了麻烦。 背景:运行 在 "use strict" 条件下的 chrome 扩展中

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' 但不知道如何创建。

我一直收到错误提示 "cannot set property 'greet' of undefined"

如何创建 属性 问候语并使代码正常工作?

谢谢!

更新这是我的代码在我的扩展程序中的样子

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

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

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

使用这个:

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

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