How Do I Access This Javascript Property?
I need to make sure that a certain method inside the below shown UserMock-class was called. I've created this mock version to inject into another module to prevent default behaviou
Solution 1:
var UserMock = (function() {
var User;
User = function() {};
User.prototype.isValid = function() {};
return User;
})();
Simply via prototype
:
(function(_old) {
UserMock.prototype.isValid = function() {
// my spy stuff
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
}
})(UserMock.prototype.isValid);
Explanation:
(function(_old) {
and
})(UserMock.prototype.isValid);
Makes a reference to the method isValue
to the variable _old
. The closure is made so we don't pulede the parent scope with the variable.
UserMock.prototype.isValid = function() {
Redeclares the prototype method
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
Calling the old method and returning the result from it.
Using apply lets put in the right scope (this
) with all the arguments passed to the function
Eg. if we make a simple function and apply it.
function a(a, b, c) {
console.log(this, a, b, c);
}
//a.apply(scope, args[]);
a.apply({a: 1}, [1, 2, 3]);
a(); // {a: 1}, 1, 2, 3
Post a Comment for "How Do I Access This Javascript Property?"