JavaScript OOP - 在基础上返回成员的Getter

时间:2014-08-07 20:14:21

标签: javascript angularjs oop

我在模型对象上实现getter和setter以在Angular中使用时遇到一些问题。我收到了这个错误:

TypeError: Cannot read property 'firstName' of undefined
at User.firstName (http://run.plnkr.co/AvdF2lngjKB76oUe/app.js:35:32)

我的代码:

angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
      var intObj = { firstName: 'Brian' };
      $scope.user = new User(intObj);
  }]);

function ModelBase(wo) {
  this.wrappedObject = wo;

  this.onPropertyChanged = function(self, propertyName, oldValue, newValue) {
    //alert(self + ", " + propertyName + ", " + oldValue + ", " + newValue);
  }
}

var isDefined = function(value) {
    return typeof value !== 'undefined';
};

User.prototype = new ModelBase();
User.prototype.constructor = User;

function User(wo) {
  ModelBase.call(this, wo);

  this.firstName = function(value) {
    if(isDefined(value))
    {
      var oldValue = this.wrappedObject.firstName;
      this.wrappedObject.firstName = value;
      //onPropertyChanged(this.wrappedObject, 'firstName', oldValue, value);
    }
    else 
    {
      return this.wrappedObject.firstName; //(Line 32)
    }
  }
}

据我所知,在实际在基础对象上设置wrappedObject之前,会调用getter。我在这里错过了什么?我已经包含了onPropertyChanged,但评论它以更好地展示我想要实现的目标。

Plunker

1 个答案:

答案 0 :(得分:2)

您在firstName方法中丢失了上下文。当Angular调用此方法时,其执行上下文是全局对象。您可以使用Function.prototype.bind方法修复它:

function User(wo) {

    ModelBase.call(this, wo);

    this.firstName = function(value) {
        if (isDefined(value)) {
            var oldValue = this.wrappedObject.firstName;
            this.wrappedObject.firstName = value;
            //onPropertyChanged(this.wrappedObject, 'firstName', oldValue, value);
        } else {
            return this.wrappedObject.firstName;
        }
    }.bind(this);
}