function myServiceFunction() {this.awesomeApi = function(optional) {// calculate some stuffreturn awesomeListOfValues;}}---------------------------------------------------------------------------------// Injected in your controller$scope.awesome = myInjectedService.awesomeApi();
或者使用工厂函数公开公共API:
function myFactoryFunction() {var aPrivateVariable = "yay";
function hello() {return "hello mars " + aPrivateVariable;}
// expose a public APIreturn {hello: hello};}---------------------------------------------------------------------------------// Injected in your controller$scope.hello = myInjectedFactory.hello();
或者使用工厂函数返回构造函数:
function myFactoryFunction() {return function() {var a = 2;this.a2 = function() {return a*2;};};}---------------------------------------------------------------------------------// Injected in your controllervar myShinyNewObject = new myInjectedFactory();$scope.four = myShinyNewObject.a2();
var Person = function(name, age){this.name = name;this.age = age;}Person.prototype.sayName = function(){alert('My name is ' + this.name);}var tyler = new Person('Tyler', 23);tyler.sayName(); //alerts 'My name is Tyler'
var Person = function(name, age){//The line below this creates an obj object that will delegate to the person's prototype on failed lookups.//var obj = Object.create(Person.prototype);
//The line directly below this sets 'this' to the newly created object//this = obj;
this.name = name;this.age = age;
//return this;}