0

https://gist.github.com/Integralist/5736427如何创建在JavaScript中战略设计模式的属性?

这部分代码从上面的链接给我带来麻烦。 背景:下一个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(); 
}; 

我想我需要创建属性“打招呼”,但不知道怎么样。

我不断收到错误说“未定义不能设置属性‘迎接’”

我怎样才能创建属性迎接并获得代码工作?

谢谢!

UPDATE,这是我的代码是如何在我的分机

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

如果不使用这个扩展,并尝试在严格模式下的其他地方,它产生相同的结果?我无法复制,但是我再也没有使用任何扩展名。 –

+0

你在做'变种G =新迎宾(someStrategy);'然后'g.greet();'?您可能需要向我们展示在您的问题中使用代码的代码。 – jfriend00

+0

是的,我使用var克=新迎宾(someStrategy);然后g.greet(); – Siddartha

回答

0

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

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

使用这样的:

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

newoperator用于从一个构造函数建立对象实例。您不需要将其用于构造函数定义。

+0

现在的伟大工程! – Siddartha