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

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

本文关键字:策略 设计模式 创建 属性 javascript      更新时间:2023-09-26

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

上面链接中的这部分代码给我带来了麻烦。背景:在"使用严格"条件下在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();
};

我想我需要创建属性"问候",但不知道如何。

我不断收到错误消息,说"无法设置未定义的属性'问候'"

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

谢谢!

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

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运算符用于从构造函数创建对象实例。不需要将其用于构造函数定义。