console.clear();
var log = function(msg) { console.log(msg); }
log("// STRATEGY AS A FUNCTION //");
// constructor
var Greeter = function(strategy) {
this.strategy = strategy;
}
// prototype
Greeter.prototype.greet = function() {
return this.strategy();
}
// functions
var politeGreetingStrategy = function() {
console.log("Hello.");
}
var friendlyGreetingStrategy = function() {
console.log("Hey!");
}
var boredGreetingStrategy = function() {
console.log("sup.");
}
// using strategies
var politeGreeter = new Greeter(politeGreetingStrategy);
var friendlyGreeter = new Greeter(friendlyGreetingStrategy);
var boredGreeter = new Greeter(boredGreetingStrategy);
// testing...
politeGreeter.greet();
friendlyGreeter.greet();
boredGreeter.greet();
// how to show benifits of these tonns of code upthere?!?
// why not just do use :)
politeGreetingStrategy();
log("// STRATEGY AS A CLASS //");
var Strategy = function() {};
Strategy.prototype.execute = function() {
throw new Error('Strategy.execute() needs to be overriden.')
}
var GreetingStrategy = function() {};
GreetingStrategy.prototype = Object.create(Strategy.prototype);
GreetingStrategy.prototype.execute = function() {
return this.sayHi() + ' ' + this.sayBye();
}
GreetingStrategy.prototype.sayHi = function() {
return 'Hello!';
}
GreetingStrategy.prototype.sayBye = function() {
return 'Bye-bye!';
}
var Greeter1 = function(strategy) {
this.strategy = strategy;
}
Greeter1.prototype.greet = function() {
return this.strategy.execute();
}
var greeter = new Greeter1(new GreetingStrategy());
log(greeter.greet());
// how to show benifits of these tonns of code upthere?!?
// why not do simplier?!?
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.