[英]Javascript prototype property defined as object
i'm trying to create a simple Person object that one of it's prototype's properties will be an object, but this doesn't seem possible because the scope changes. 我正在尝试创建一个简单的Person对象,该对象的原型属性之一将是一个对象,但这似乎不可能,因为范围发生了变化。
var Person = function() {};
Person.prototype.set = function(data) {
this.data = data;
};
Person.prototype.update = {
name: function(name) {
this.data.name = name;
}
};
var me = new Person();
me.set({name: 'Achilleas'});
me.update.name('John');
You can also run it on this jsFiddle 您也可以在此jsFiddle上运行它
Is what I want to achieve possible? 我想实现的目标可能吗? I know i can do it by using apply to assign the scope, but i don't really like this solution.
我知道我可以通过使用apply来分配作用域来做到这一点,但是我真的不喜欢这种解决方案。
Thank you for spending time on my first question on Stackoverflow. 感谢您花时间在我关于Stackoverflow的第一个问题上。
The issue your experiencing is caused because this
will refer to the object literal that is created and assigned to the update
property. 引起您遇到的问题,因为
this
将引用创建并分配给update
属性的对象文字。 It does not refer to person. 它不是指人。 Therefore, referring to
this.data.name
produces an error since the object literal does not have a data property. 因此,引用
this.data.name
会产生错误,因为对象文字没有数据属性。
I would recommend just extending the prototype of Person
to include an update method which takes a property to update and a value. 我建议只扩展
Person
的原型,使其包含一个update方法,该方法需要一个属性来更新和一个值。 Also add data
as a property of person. 还要将
data
添加为个人的财产。
var Person = function() {
this.data = {};
};
Person.prototype.set = function(data) {
this.data = data;
};
Person.prototype.update = function(property, value){
this.data[property] = value;
};
var me = new Person();
me.set({name: 'Achilleas'});
me.update('name','John');
Working Example http://jsfiddle.net/fj5uY/7/ 工作示例 http://jsfiddle.net/fj5uY/7/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.