如何在该var中定义的函数中设置var属性?

时间:2014-04-09 04:08:53

标签: javascript

我对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怎么可能?

3 个答案:

答案 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 关闭的行为。

基本上,函数可以访问函数范围之外的变量。如果这些变量发生变化,它就会随处变化。

  1. 创建函数后,service仍为undefined
  2. 这些函数围绕service变量
  3. 创建闭包 然后将
  4. service指定为对象
  5. 所有功能现在都指向service对象
  6. 这是一种可视化的方法:

    var service = null;
    var getService = function() { return service; };
    
    service = 5;
    getService(); // returns 5
    
    service = "service can change";
    getService(); // returns "service can change";