Get context of a function? - javascript

I'm using Jasmine to do unit tests and I am spying on a function:
it('should loop through all inputs', function() {
var test = function() {};
spyOn(this, 'test').andCallThrough();
formManager.eachInputs($unfoldedView, test);
expect(test).toHaveBeenCalled()
});
My problem is that the spyOn takes two parameters: (context, function). What is the context of the test function and how do I get it? It's context is the inside of this anonymous function, but I don't know how to get that. (I wrote this as the context parameter, but it's not that)

When you're in the global scope, your declared variables exist as members on the global object (either window or global). When you declare variables in a local function scope, there is no analogous "local" object. (See the Stack Overflow question "JavaScript: Reference a functions local scope as an object" for more details.)
Instead, you can make your function a method of an object and use that object as the context:
it('should loop through all inputs', function() {
var obj = { test: function() {} };
spyOn(obj, 'test').andCallThrough();
formManager.eachInputs($unfoldedView, obj.test);
expect(obj.test).toHaveBeenCalled()
});

Related

Immediately Invoked functions in javascript

I have a clarification in using IIFs in javascript .
I have downloaded a javascript file called called test.js as follows and I have got following questions after googling IIFs:
define(function () {
(function (window) {
this.test = function() {};
Test.prototype.function1 = function(){
//Do something
},
function Delete(){
//Code to Delete
}
window.Delete = Delete;
})(window);
});
I do have the following questions:
Is the line,
this.test = function() {}; a constructor?
If so can I have 2 constructors in a single file like for example:
this.test = function() {};
this.test2 = function() {};
And also, why would I need a constructor when I know that this is an automatically invoked file where everything gets executed initially itself.
Is this a private function?
Test.prototype.function1 = function(){
//Do something
},
Does this not get automatically? Should I need to create an object of the test and then invoke it?
Is this a public function?
function Delete(){
//Code to Delete
}
window.Delete = Delete;
The last line of the above says that . If it is so then whats the difference between first and second function?
What is keyword window here?
It's worth noting that this code will fail with an error, as Test is undefined, and you can't set the prototype property on undefined.
In JavaScript, any function can be a constructor. It's up to how you use it. You can add functions and properties to the .prototype property of any function, and any objects created from it using new will get them from the prototype chain. In your case, this.test = function(){} doesn't look like a prototype.
There's no such things a "public" or "private" functions in JavaScript, there's only what's exposed via return out of the function (or in your case, by using the global window object, which is considered bad practice) If the Test function is exposed somewhere, then Test.prototype.function1 is also exposed. All prototype methods are "public".
Yes, sort of. Like I said, "public" or "private" isn't a thing in JavaScript. You created a function and placed it on the window object, which is global. Essentially, you've made the function global.
window is the global browser object. Although when used like this (function(window) { ... })(window), the first window is the name of the parameter, (and any instances of window inside the function reference to that parameter, and the second one (passed to the function call), is the global window object.
Further reading:
The Revealing Module Pattern

QUnit: How to pass a global variable reference?

I have a qunit module that doesn't allow a created object's method to see a global variable. The simplified version:
qunit.module("testcases", {
setup: function () {
var globalVar = "something";
}
});
test("test1", function () {
obj = new MyObj({});
obj.execute(); // uses globalVar but doesn't see it
});
How can I get the obj instance to recognize the globalVar?
I tried defining globalVar within test1 as well, but no luck. I don't want to put the globalVar on the obj instance, since it's execute function doesn't check on itself for the global
As mentioned by anonymous superuser -- cannot use var in the setup function because it's actually closed off as it's own scope

Can a parameter be passed to a function that is set as an object literal value?

I have a function, functionWithDifferentScope, that takes an object, myobject.options, as a parameter. One of the pairs in the options object is a callback which points to a function defined in myObject: myCallback.
What I'm trying to achieve is injection of the myObject namespace into the callback of a function that is defined (by a 3rd party) at the global level.
A simplified example:
var myObject = {
options: {
callback: this.myCallback(this),
...,
},
init: function() {
// functionWithDifferentScope operates in the 'window' context
functionWithDifferentScope(this.options);
},
myCallback: function(namespace) {
// 'this' is window
// 'namespace' is myObject
}
}
myObject.init();
When executing this script, this.myCallback(this) appears to be executed at definition (due to the parenthesis?); as well as once myObject.init(); is caled. During the first executions this is myObject, but subsequent calls through the functionWithDifferentScope identify this as window.
Is there a way to pass the myObject namespace to the myObject.options.callback value as a parameter?
Do you mean this?
var myObject = new (function() {
var t = this;
vac callback = function() {
// t equals to the myObject-instance
// this equals to window
}
this.init = function() {
funcWithDifferencScope(callback);
}
})();
myObject.init();
I think what you are looking for is prototype style "bind"
Basically "this.myCallback(this)" is a call to the function.
this.myCallback is the function itself. (It is an object with the type function).
You can call it using the method 'call' or 'apply' that you can use on functions. Which will call these functions.
See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fapply
The first argument is the object context to work in. What I think you mean by object namespace.
so: a.callback(5) is the same as a.callback.call(a,5)
However please note that these days if you are working with most javascript libraries you probably have a 'bind' function that will do the work for you.
http://prototypejs.org/doc/latest/language/Function/prototype/bind/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
the idea is that this.callback.bind(this) returns a Function object you can call that will inject the correct context automatically so you can pass the return value of bind alone as a callback and be assured that the method will be executed on the correct object.

"this" keyword in a javascript module

I have defined the following module globally:
var module = (function () {
console.log(this);
this.fn = function () {
console.log(this);
}
return this;
})();
http://www.quirksmode.org/js/this.html :
In JavaScript |this| always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.
The first call to console.log logs Window as the value of this, and that I understand. But, so does also the second call to console.log.
Since this refers to the owner of the function, why does module.fn log Window and not module?
When I call fn I still have to write module.fn, I can't write Window.fn. Since this refers to Window I find this confusing.
EDIT: I forgot to return this in my example.
Since this refers to the owner of the function, why does module.fn log Window and not module?
The return value of the outer function is window because it doesn't get called in any particular context, so module ends up being window as well.
It seems that the way you have applied the module pattern is wrong. It should be returning the public interface that gets used in the rest of your code:
var module = (function () {
console.log(this);
// public interface
return {
fn: function () {
console.log(this);
}
}
})();
module.fn(); // "Object {fn: function}"
In your example, the global object receives the fn. It is the window object in case of browsers. That is because you are calling the function in place (effectively constructing a new scope) without specific context.
On the end, your module object is just a reference to the window (because of return this;).
What is this?
In JavaScript, this is the current context, the object on which the function was called that particular time. It is not the "holder" of the function. You can always "steal" the method from other objects and apply (literally) it to your own.
Assume you want to slice the arguments object for some reason. It looks just like an array, but it is NOT an array. arguments.slice(2,4) does not work (assuming ECMAScript < 5). What to do?
Array.prototype.slice.apply(arguments, [2,4]);
You need to steal the slice function from the Array prototype, and use if on your arguments. Inside the slice call, the "this" is the arguments object that particular time.
How to construct a valid module?
Your job is to return the module object. You do not want do mess with the context. It is not relevant, as long as you are not applying the function directly on module object.
The easiest solution is the simplest.
var module = (function() {
// do something internally, great for "private" stuff
// then return the "public" interface
return {
doSomething: function() {
// do something
},
introduce: function() {
console.log(this);
}
};
})();
module.introduce(); // Object {doSomething: function, introduce: function}
module.doSomething();
The other way.
Alternatively, you could use the this to do your job, using the apply, if you really want to.
var module = {};
(function(){
this.doSomething = function() {
// do something
};
this.introduce = function() {
console.log(this);
};
}).apply(module);
module.introduce(); // Object {doSomething: function, introduce: function}
module.doSomething();
Note this is almost equal to the "new" call.
There are more equally valid ways to do it, but the first presented one is frequently used and very clear. Anyway, everything really depends on your code conventions.
Your pattern is wrong what you are doing to make a closed scope and setting module to the return from that scope:
// This is the design pattern:
var module = (function () {
var module = {};
var localVar = 1;
module.moduleVar = 2;
module.fn = function () {
console.log(this);
}
return module;
})();
console.log(module.fn); // function() { console.log(this) ;}
console.log(module.moduleVar); // 2
console.log(module.localVar); // undefined

javascript how to get this.variable in callback function

In the following customized class in javascript, in callback, why does this.obj have nothing but local variable obj has thing I want? Thanks.
function ClassTest(director) {
this.obj = {"test1": "test1"};
}
function test1(input, callback) {
callback("success");
}
ClassTest.prototype.test = function() {
var obj = this.obj;
test1("niuniu",function(e){
console.log(this.obj); // undefined
console.log(obj); // this one has stuff
});
}
// run
new ClassTest().test()
Because the function inside test1 is creating a new scope with different this context. Typical solutions are to bind or to cache this:
Binding:
test1("niuniu",function(e){
console.log(this.obj);
}.bind(this));
Caching:
var self = this;
test1("niuniu",function(e){
console.log(self.obj);
});
As for this line of code:
console.log(obj); // this one has stuff
The reason it works has to do with how JavaScript closure works. The code defined in your anonymous function has access to all variables in its local scope as well as variables defined in encompassing scopes and therefore obj is available. See How do JavaScript closures work? for more on closure.
The keyword this however, is a reference to the current scope. Because you are accessing this.obj from within the anonymous function, this refers to the anonymous function itself - which has no obj property defined. In the enclosing function, which is extending the ClassTest prototype, this refers to the current ClassTest object, which does have a obj property defined.

Categories