Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
var $providers = {},
    $instances = {};
function provider(name, providerFn) {
  var providerName = name + 'Provider';
  if (typeof providerFn !== 'function') {
    return $providers[providerName];
  }
  
  providerFn.name = name;
  $providers[providerName] = new providerFn();
}
function factory(name, factoryFn) {
  provider(name, function () {
    this.$get = factoryFn;
  });
}
function service(name, serviceConstructor) {
  factory(name, function () {
    return new serviceConstructor();
  });
}
function getInstance(name) {
  if ($instances.hasOwnProperty(name)) {
    return $instances[name];
  }
  var providerInstance;
  if (undefined === (providerInstance = provider(name))) {
    throw new Error("Provider for service \"" + name + "\" not found!"); 
  }
  $instances[name] = providerInstance.$get();
  
  return $instances[name];
}
// примеры:
service('foo', function () {
  this.foo = function () {
    return 'foo';
  };
});
var 
   fooInstance1 = getInstance('foo'),
   fooInstance2 = getInstance('foo')
;
console.log(fooInstance1.foo());
console.log(fooInstance1 === fooInstance2);
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers