Getters and Setters on angular.extend $scope

Getters and Setters on angular.extend $scope

本文关键字:extend scope angular on and Setters Getters      更新时间:2023-09-26

我正在阅读一篇有趣的文章AngularJS:Tricks with angular.extend(),并解释了如何使用getterssettersextend。但有些观点我不明白。

Js:

app.controller('ThingController', [ '$scope', function($scope) {
    // private
    var _thingOne = 'one',
        _thingTwo = 'two';
    // models
    angular.extend($scope, {
        get thingOne() {
            console.log("get thing1");
            return _thingOne + 'eeeeee';
        },
        set thingOne(value) {
            console.log("set thing 1");
            if (value !== 'one' && value !== 'two'){
                throw new Error('Invalid value ('+value+') for thingOne');
           }
        },
        get thingTwo() {
            console.log("get thing2");
            return _thingTwo + 'oooooo';
        },
        set thingTwo(value) {
            console.log("set thing 2");
            if (value !== 'two' && value !== 'three'){
                throw new Error('Invalid value ('+value+') for thingTwo');
           }
        }
   });
    // methods
    angular.extend($scope, {
       get things() {
            return _thingOne + ' ' + _thingTwo;
        }
    });
}]);

目录:

<body ng-controller="ThingController">
    {{ things }} // one, two 
</body>

我的问题:

  1. ¿为什么get thingOne()不返回oneeeeeee?(get thingTwo()也一样)

  2. ¿哪里叫set thingOneset thingTwo?因为我从来没有在控制台上看到set thing 1set thing 2.

  3. ¿
  4. 如何在angular.extend methods内声明set method? ¿是否可以从视图中断言值?

试试这个方式:

angular.extend($scope, {
    get things() {
        return $scope.thingOne + ' ' + $scope.thingTwo;
    }
});

在这种情况下,将调用 Setter:

$scope.thingOne = 'test';

它与 angular.extend 无关 - 这些是属性访问器:getter 和 setter...允许您在对象字段的读/写中添加一些逻辑。

以下是您定义一个的方法:

var instance = {
   get prop() { return this._prop },
   set prop(value) { this._prop = value }
}

像这样使用它:

instance.prop = "new value"
var x = instance.prop

angular.extend仅将此定义复制到$scope。您也可以使用Object.define。如图所示:http://jsfiddle.net/v1bxyrx1/2/