【问题标题】:JavaScript OOP - Getter that returns member on baseJavaScript OOP - 返回基础成员的 Getter
【发布时间】:2014-08-07 20:14:21
【问题描述】:

我在我的模型对象上实现 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)
    }
  }
}

据我所知,getter 是在 WrapObject 实际设置在基础对象上之前被调用的。我在这里想念什么?我已包含 onPropertyChanged,但将其注释掉以更好地展示我想要完成的工作。

Plunker

【问题讨论】:

  • 这个标题有误导性
  • 我会将User 定义为可用于获取/操作User的服务
  • @true: 怎么样? WrappedObject 是 ModelBase 的成员,不是吗?
  • 您需要在firstName 方法之前为this 设置标志。喜欢:var self = this 然后在firstName 方法中使用self 而不是thisplnkr.co/edit/htJLOyGItYHLa6EO7Vgo?p=preview
  • @RahilWazir:这解决了它,谢谢。我对 JavaScript 中“this”的使用感到有些困惑。我将不得不阅读。请回答,我会接受的。

标签: javascript angularjs oop


【解决方案1】:

您在 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);
}

【讨论】:

  • 这是“角度方式”吗?我问是因为我觉得这应该以其他方式编码。
  • @JohnSterling Angular 本身就是 JavaScript。这样做很好。
  • 嗯,是的,但这不是我问的。我想知道在 Angular 中是否有更好的方法来处理这类事情。
  • @JohnSterling 我不确定你想用你的代码做什么,但是从 Angular 的角度来看它看起来有点尴尬。完全不知道为什么需要这个包装模型构造函数。
  • 我不是问这个问题的人,只是觉得这一切看起来很奇怪。
猜你喜欢
  • 2012-05-28
  • 2019-01-31
  • 2013-07-09
  • 2011-07-05
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
相关资源
最近更新 更多