javascript AngularJS 的 getter/setter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25452989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:31:56  来源:igfitidea点击:

AngularJS getter / setter

javascriptangularjssettergetter

提问by Chris Dunom

I'm learning angular and I'm trying to figure out what is the best solution to use getters/setter.

我正在学习 angular,并试图找出使用 getter/setter 的最佳解决方案。

Saying, I'm using a library which exposes getters and setters (as Moment.js does).

说,我正在使用一个公开 getter 和 setter 的库(就像 Moment.js 那样)。

I've tried several ways to deal with getters and setters, here they are:

我尝试了几种方法来处理 getter 和 setter,它们是:

index.html

索引.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Example - example-ngModel-getter-setter-production</title>
  <script data-require="[email protected]" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js">    </script>
  <script src="app.js"></script>
</head>

<body ng-app="getterSetterExample">
  <div ng-controller="ExampleController">
    <form name="userForm">
      Name :
      <input type="text" name="userName" ng-model="user.name" ng-model-options="{ getterSetter: true }" />
      <br/>Name1:
      <input type="text" name="userName1" ng-model="user1.name" ng-model-options="{ getterSetter: true }" />
      <br/>Name2:
      <input type="text" name="userName2" ng-model="user2.name" ng-model-options="{ getterSetter: true }" />
      <br/>Name3:
      <input type="text" name="userName3" ng-model="user3.name" ng-model-options="{ getterSetter: true }" />
    </form>
    <pre>user.name =         <span ng-bind="user.name()"></span>
      </pre>
    <pre>user1.name =        <span ng-bind="user1.name()"></span>
      </pre>
    <pre>user2.name =        <span ng-bind="user2.name()"></span>
      </pre>
    <pre>user3.name =        <span ng-bind="user3.name()"></span>
      </pre>
  </div>
</body>

</html>

app.js

应用程序.js

  angular.module('getterSetterExample', [])
    .controller('ExampleController', ['$scope',
      function($scope) {
        var _name = 'Brian';
        var _name3 = 'Joe';


        var name1 = {
          _name: 'George',
          name:function(newName) {
            if (angular.isDefined(newName)) {
              this._name = newName;
            }
            return this._name;
          }
        };

        var name2 = {
          _name: 'Michael',
          name:function(newName) {
            if (angular.isDefined(newName)) {
              this._name = newName;
            }
            return this._name;
          }
        };

        var name3 = {
          name:function(newName) {
            if (angular.isDefined(newName)) {
              _name3 = newName;
            }
            return _name3;
          }
        };

        $scope.user = {
          name: function(newName) {
            if (angular.isDefined(newName)) {
              _name = newName;
            }
            return _name;
          }
        };

        $scope.user1 = {
          name: name1.name
        };

        $scope.user2 = {
          name: function(newName) {
            return name2.name(newName);
          }
        };

        $scope.user3 = {
          name: name3.name
        };

      }
    ]);

You can try it here: http://plnkr.co/edit/S1qKre9umNpLOt0sjpZf?p=preview

你可以在这里试试:http: //plnkr.co/edit/S1qKre9umNpLOt0sjpZf?p=preview

2 Questions:

2 问题:

user1 tries to direcly use the getter/setter provided by the name1 objet, it doesn't work properly, can you explain why?

user1 试图直接使用 name1 对象提供的 getter/setter,它不能正常工作,你能解释一下为什么吗?

Is there a way to avoid to rewrite a "proxy" for each getter/setter as I've done in user3? what would be the best method to use getters/setters provided by an external library?

有没有办法避免像我在 user3 中所做的那样为每个 getter/setter 重写“代理”?使用外部库提供的 getter/setter 的最佳方法是什么?

Thank for your help

谢谢您帮忙

回答by PSL

user1 tries to direcly use the getter/setter provided by the name1 objet, it doesn't work properly, can you explain why?

user1 试图直接使用 name1 对象提供的 getter/setter,它不能正常工作,你能解释一下为什么吗?

The issue is with the context, You are just merely copying the function reference name1.nameby doing:-

问题在于上下文,您只是name1.name通过执行以下操作来复制函数引用:-

    $scope.user1 = {
      name: name1.name
    };

so when it is run thisin the getter will actually point to the window/global (in non strict mode). You can workaround this by using Function.bind.

所以当它this在 getter 中运行时实际上会指向window/global(在非严格模式下)。您可以使用Function.bind解决此问题。

Example:-

例子:-

    $scope.user1 = {
      name: name1.name.bind(name1)
    };

Demo

演示

Is there a way to avoid to rewrite a "proxy" for each getter/setter as I've done in user3?

有没有办法避免像我在 user3 中所做的那样为每个 getter/setter 重写“代理”?

I would just create a wrapper so that i don't run into context issues like these.

我只想创建一个包装器,这样我就不会遇到这样的上下文问题。

    $scope.user = getModel('name', 'Brian');

    $scope.user1 = getModel('name', 'George');

    $scope.user2 = getModel('name', 'Michael');

    $scope.user3 = getModel('name', 'Joe');

    $scope.address = getModel('address');


  //You can improve this by passing an optional getter functionality as well for some specific evaluation on the value when set.
  function getModel(propertyName, defValue) {
      var obj =  {};

      obj._defVal = defValue;
      obj[propertyName] = function(newVal){
        if (angular.isDefined(newVal)) {
          obj[prop] = newVal;
        }
        return obj[prop];
      }

      return obj;
    }
   }

Or just

要不就

 function getModel(propertyName, defValue) {
      var obj =  {};
       var propValue = defValue;
      obj[propertyName] = function(newVal){
        if (angular.isDefined(newVal)) {
          propValue = newVal;
        }
        return propValue;
      }
      return obj;
    }
  }

Demo2

演示2