Reputation: 3685
I'm very new to JS and I have been playing around with Jasmine.
In Jasmine, I can see a method called spyOn
, which does inspect/spy the functions.
How does this works in js? Coming from Java background is it a proxy? How to write one?
Upvotes: 1
Views: 255
Reputation: 50958
You can find the precise implementation on GitHub, but here is a simplified explanation:
function mySpy(obj, methodName) {
// remember the original method
var originalMethod = obj[methodName];
// ... then replace it with a method that ...
obj[methodName] = function () {
// ... does whatever additional thing it wants to do ...
console.log(methodName + " called, first argument: " + arguments[0]);
// ... and then calls the original method with the same arguments,
// and returns the result.
return originalMethod.apply(this, arguments);
};
}
Now you can do this:
var o = {
inc: function (x) { return x + 1; }
};
mySpy(o, "inc");
console.log(o.inc(13));
This will output
inc called, first argument: 13
14
Three important things for you to know, coming from a Java background, are
someObj.someMethod = someOtherFunction
is perfectly valid. (To be 100% precise, you may not actually be overwriting the original method, because it may be somewhere up the prototype chain, instead of on the object itself. That's an advanced topic though, and not very important here. Also, Java's distinction beween methods and class members doesn't apply to JavaScript.)arguments
inside a function contains whatever arguments the function was called with. In Java terms, imagine that someMethod(Foo x1, Bar x2)
always has an implicit second signature of the type someMethod(Object... arguments)
, meaning you could always use x1
and arguments[0]
interchangeably.obj.someName
and obj["someName"]
are entirely equivalent in JavaScript. Because of this, you can easily access/change an object's properties using the property name as a string, something that in Java you would have to use reflection for.Upvotes: 2