JavaScript OOP-返回基上成员的Getter
在Angular中使用的模型对象上实现getter和setter时遇到一些问题。我得到这个错误:JavaScript OOP-返回基上成员的Getter,javascript,angularjs,oop,Javascript,Angularjs,Oop,在Angular中使用的模型对象上实现getter和setter时遇到一些问题。我得到这个错误: TypeError: Cannot read property 'firstName' of undefined at User.firstName (http://run.plnkr.co/AvdF2lngjKB76oUe/app.js:35:32) 我的代码: angular.module('getterSetterExample', []) .controller('ExampleCon
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是在wrappedObject实际设置在基本对象上之前被调用的。我错过了什么?我已经包括了onPropertyChanged,但对其进行了注释,以更好地显示我正在努力实现的目标
您在
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);
}
这个标题有误导性,我会将
用户
定义为一种可用于获取/操纵用户
@true:Howso?wrappedObject是ModelBase上的成员,不是吗?您需要在firstName
方法之前为this
设置标志。例如:var self=this
然后在firstName
方法中使用self
而不是this
@拉希尔瓦齐尔:那就解决了,谢谢。我对JavaScript中“this”的用法有点困惑。我得仔细阅读一下。请回答,我会接受的。不过这是‘棱角分明的方式’吗?我这样问是因为我觉得应该用其他方式来编码。@JohnSterling Angular本身就是JavaScript。这样做很好。嗯,是的,但我不是这么要求的。我想知道是否有更好的方法在角度上处理这类内容。@JohnSterling我不确定您试图用代码做什么,但从角度上看,它看起来有点笨拙。我根本不知道你为什么需要这个包装器模型构造函数。我不是那个问这个问题的人,只是觉得这一切看起来很奇怪的人。