【发布时间】: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,但将其注释掉以更好地展示我想要完成的工作。
【问题讨论】:
-
这个标题有误导性
-
我会将
User定义为可用于获取/操作User的服务 -
@true: 怎么样? WrappedObject 是 ModelBase 的成员,不是吗?
-
您需要在
firstName方法之前为this设置标志。喜欢:var self = this然后在firstName方法中使用self而不是this。 plnkr.co/edit/htJLOyGItYHLa6EO7Vgo?p=preview -
@RahilWazir:这解决了它,谢谢。我对 JavaScript 中“this”的使用感到有些困惑。我将不得不阅读。请回答,我会接受的。
标签: javascript angularjs oop