The is example #81 from John Resigs Learning Advanced JavaScript, called Beware: Extending Prototypes Can Be Dangerous.http://ejohn.o开发者_开发百科rg/apps/learn/#81 As it is written (length == 3), the assert fails, but if you assert obj.keys().length == 4
it passes.
Here are some questions
1) Why is he saying "We should only have 3 properties"? In what way was it unexpected or disappointing to have 4 properties?
2) How does it get 4 properties?
3) What is var i
in the third line of the program?
4) Does this
in the third line refer to Object?
5) Looking at the assert, does this code obj.keys().length
call the function in the first line?
6) If there are 4 properties in obj.keys().length, are there also 4 elements in the returned array var keys once it is returned?
Object.prototype.keys = function(){
var keys = [];
for ( var i in this )
keys.push( i );
return keys;
};
var obj = { a: 1, b: 2, c: 3 };
assert( obj.keys().length == 3, "We should only have 3 properties." );
delete Object.prototype.keys;
1) It would be reasonable, looking at the initializer, to expect that a fresh new Object would only have the properties that you have assigned to it. Reasonable, but wrong. In javascript, the prototype chain causes objects to "inherit" properties that are not initialized on each instance.
2) The fourth item is the keys()
function that was just defined on Object
.
3) var i
is just a loop variable.
4) this
refers to whatever object the function is being called against. So if you call a.keys()
, then this
is a
.
5) Yes.
6) Yes — but since it is a local array, it is out of scope once it is returned so it can only be accessed if the return value was assigned to another variable in the calling function.
精彩评论