How do I refactor the updating of object properties?
I have a JavaScript object those properties are static, mostly. They can be determined at construction time. However, I've also added a method "morph" that changes the object's state. So these properties should change along with it.
I've coded it successfully below, as a method (longNameMethod, no problems) and as a property (longNameProperty, problematic). The problem with longNameProperty is that there is code in the constructor and in the morph method that looks very similar. Is there a way to eliminate this duplication?
var Fruit = function (name) {
this.name = name;
this.longNameMethod = function () {
return this.name + this.name;
}
this.longNameProperty = this.name + this.name;
this.morph = function(name) {
this.name = name;
// starting to feel redundant
this.longNameProperty = this.name + this.name;
}
// update(); // hypothetical solution
};
var item = new Fruit('apple');
console.log(item.longNameMethod()); // apple apple
console.log(item.longNameProperty); // apple apple
item.morph('orange');
console.log(item.longNameMethod()); // orange orange
console.log(item.longNameProperty); // orange orange
I tried including an "update" method that would handle updating all of these pr开发者_C百科operties but for some reason I can't use it during construction. It says that this.name is undefined. What's up with the order of operations during construction?
Edit: So yes, the method approach and the property approach are functionally identical to the outside, but the goal is to use the property approach.
Edit^2: So I think there are multiple issues at play... One of which is explained here: How does "this" keyword work within a function?
You need to add the method before using it, when you assign it into this
:
var Fruit = function (name) {
this.morph = function(name) {
this.name = name;
this.longNameProperty = this.name + this.name;
}
this.morph(name);
};
var item = new Fruit('apple');
console.log(item.longNameProperty); // apple apple
item.morph('orange');
console.log(item.longNameProperty); // orange orange
精彩评论