JavaScript receivers / setters and extenders

I study getters and setters in JavaScript and how well they work with advanced functions for extending objects like jQuery $ .extend and Underscore _.extend. The code setup is as follows:

var test = { get size() { return this._size; }, set size(val) { this._size = val; }, } test.size = "LARGE"; console.log(test.size); //$.extend(test, { get size() { return "MEDIUM"; } }); _.extend(test, { get size() { return "MEDIUM"; } }); console.log(test.size); test.size = "SMALL"; console.log(test.size); 

In Chrome and Firefox, I get:

 LARGE MEDIUM SMALL 

Can someone explain to me what is going on there? Why is the original receiver also restored after calling the original setter?

+6
javascript extend setter getter
source share
1 answer

The underline of extend as follows:

  _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { for (var prop in source) obj[prop] = source[prop]; }); return obj; }; 

Iterates over the properties of the source object, adds them to the target object, and then returns the target object. When it copies the size property to the object you are distributing, it basically does this:

 obj['size'] = source['size'] 

That is, it uses the new getter object, but only copies the value returned by this recipient. It does not pass the getter itself.

To demonstrate this, try the following:

 var test = { get size() { return this._size; }, set size(val) { this._size = val; }, } for (var p in test) { console.log(p) } 

Which outputs only:

 size 

(He does not iterate over getters or setters.)

+5
source share

All Articles