Can anyone explain how the getDecorator and tree.BlueBalls functions work? How do these function modify the tree object?
var tree = {};
tree.decorate = function() {
alert('Make sure the tree won\'t fall');
};
tree.getDecorator = function(deco){
tree[deco].prototype = this;
return new tree[deco];
};
tree.BlueBalls = function() {
this.decorate = function() {
this.BlueBalls.prototype.decorate();
alert('Add blue balls');
}
};
tree = tree.getDecorator('BlueBalls');
tree.decorate()
The decorator function creates a new object (which is essentially a new property for the tree object) Blueballs
which has tree as its prototype and returns it.
Now if you call the newly created object, it will first invoke its prototype's decorate
function ( this.BlueBalls.prototype.decorate()
) and then its own decorate
function, resulting in the two alerts 'Make sure the tree won\\'t fall' and 'Add blue balls'.
For those who are not familiar with the design pattern: The decorator pattern essentially adds behavior to an existing object by creating a "wrapper", so it does not affect the behavior of the original object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.