我对AngularJS中的工厂定义有疑问。我不确定这是一个Javascript疑问还是AngularJS,但我相信它是Angular。
说我有这样的工厂定义:
angular.module('myApp.services')
.factory('User', function($http) { // injectables go here
var backendUrl = "http://localhost:3000";
var service = {
// our factory definition
user: {},
setName: function(newName) {
service.user['name'] = newName;
},
setEmail: function(newEmail) {
service.user['email'] = newEmail;
},
save: function() {
return $http.post(backendUrl + '/users', {
user: service.user
});
}
};
return service;
});
如果service.user['email']
实际定义service
本身,函数setName能够设置setName
怎么可能?
答案 0 :(得分:1)
这是基本的javascript。忘记工厂一分钟,只考虑service
的定义。
var service = {
//service will have an empty user js object
user: {},
//a key setName with the value as a function
//which sets a key value pair in user defined above
//service = { user: {name: 'Tony'} }
setName: function(newName) {
service.user['name'] = newName;
},
//a key setEmail with the value as a function
//which sets a key value pair in user defined above
//(consider setName has been called already)
//service = { user: {name: 'Tony', email: 'tony@stark.com'} }
setEmail: function(newEmail) {
service.user['email'] = newEmail;
},
//a key save with the value as a function
//which saves
save: function() {
//return something from a call mimicing $http.post
//return $http.post(backendUrl + '/users', { user: service.user });
}
}
然后,返回或使用已成为API的service
。
查看开发工具控制台以登录此FIDDLE
答案 1 :(得分:0)
setName
函数将被其他一些代码调用,
User.setName("newname ");
在调用service
时已经定义了它,并且关于为属性设置新值。
您可以使用this
关键字使代码更有意义,
setName: function(newName) {
this.user['name'] = newName;
}
我发现您的代码存在一个问题,即使您定义了setName
函数,您也可以在工厂外访问user
变量,现在您也可以这样做,
User.user['name'] = newName;
我认为您需要做的是将user
设为私有变量,
angular.module('myApp.services')
.factory('User', function($http) { // injectables go here
var backendUrl = "http://localhost:3000";
var user={};
var service = {
// our factory definition
setName: function(newName) {
user['name'] = newName;
},
setEmail: function(newEmail) {
user['email'] = newEmail;
},
getUser:function(){
return user;
},
save: function() {
return $http.post(backendUrl + '/users', {
user: service.user
});
}
};
return service;
});
答案 2 :(得分:0)
您所描述的是JavaScript 关闭的行为。
基本上,函数可以访问函数范围之外的变量。如果这些变量发生变化,它就会随处变化。
service
仍为undefined
service
变量service
指定为对象service
对象这是一种可视化的方法:
var service = null;
var getService = function() { return service; };
service = 5;
getService(); // returns 5
service = "service can change";
getService(); // returns "service can change";