Search code examples
javascriptdesign-patternsgoogle-chrome-extensionpropertiesstrategy-pattern

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


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

this part of the code from the link above is giving me trouble. background: running in a chrome extension under "use strict" conditions

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();
};

I think i need to Create the property 'greet' but don't know how to.

I keep getting error saying "cannot set property 'greet' of undefined"

How can I create the property greet and get the code to work?

Thanks!

UPDATE this is how my code is in my extension

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

Solution

  • The problem is in the constructor definition MessageHandling. You need to remove the new keyword, because it doesn't make sense here.
    Instead of this code:

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

    use this:

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

    The new operator is used to create object instances from a constructor function. You don't need to use it for constructor definition.