I'm attempting to write a node module in order to clean up my code and separate it out into different files.
Consider the below code:
module.exports = {
Hello : function(request, reply) {
return reply("Hello " + World());
},
World : function() {
return "World";
}
}
If I import the above module and use the Hello function as handler for a specific route, i get an HTTP 500 internal server error.
I've narrowed the problem down to the call to World(), if I change the Hello function to
Hello : function(request, reply) {
return reply("Hello World");
}
Then it works fine, so it seems that it is being tripped up when calling another function from within the export object
Does anyone know why this is happening and how to resolve it?
You should call it as follows:
module.exports = {
Hello: function(request, reply) {
return reply("Hello " + module.exports.World());
},
World: function() {
return "World";
}
}
If you are aiming for cleaner code, I suggest that you change the code to this:
function World() {
return "World";
}
function Hello(request, reply) {
return reply("Hello " + World());
}
module.exports = {
Hello,
}
This will make your code more readable and you will only be exporting what you actually need. This question has other solutions to your issue.
Well let's demonstrate the this
this doesn't define the object that the function resides in. It defines from where the function is called. So while;
var obj = {
Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
};
obj.Hello("test", console.log);
would work just fine; This wouldn't;
var obj = { Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
};
setTimeout(obj.Hello,100,"test",console.log);
This is just because the obj.Hello will be assigned an argument in setTimeOut function's definition and that argument will be invoked as window being the this for that function. So you should instead do like;
var obj = { Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
};
setTimeout(obj.Hello.bind(obj),100,"test",console.log);
//or
setTimeout(obj.Hello.bind(obj,"test",console.log),100);
//or
setTimeout((x,y) => obj.Hello(x,y),100,"test",console.log);
You'll need to add this to your invocation of World() -
module.exports = {
Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
}
World is an attribute of the export object, not a variable within the accessible scope - so you need to specify that the function belongs to this.
Related
I have some page object document with code:
var gmailItemClicks = {
composeClick: function () {
return this.section.leftToolbarSection.click('#compose');
}
};
module.exports = {
commands: [gmailItemClicks],
sections: {
leftToolbarSection: {
selector: '.nH.oy8Mbf.nn.aeN',
elements: {
compose: { selector: '.T-I.J-J5-Ji.T-I-KE.L3' },
}
},
};
and the test file with many steps, like this:
module.exports = {
'1st step': function (client) {
gmail.composeClick();
},
'2d step': function (client) {
gmail.composeClick();
}
}
i can use 'gmail' variable if it is in every step like this:
module.exports = {
'1st step': function (client) {
var gmail = client.page.gmail();
gmail.composeClick();
},
'2d step': function (client) {
var gmail = client.page.gmail();
gmail.composeClick();
}
}
but i want to separate this var from the test code in the steps. I tried to use
const gmail = require('./../pages/gmail');
in the test before module.exports bloсk, and i tried to use globals.js file with the same syntax, but i get the error " ✖ TypeError: gmail.composeClick is not a function".
Now i have just one big function where are all steps used variable declared once inside the func, but the log of test looks ugly, i cant to see when the one step started and where it was stopped.
What i missed?
you could create the object in the before block. Here is how it would look like in my code:
(function gmailSpec() {
let gmailPage;
function before(client) {
gmailPage = client.page.gmail();
gmailPage.navigate()
}
function after(client) {
client.end();
}
function firstStep() {
gmailPage.composeClick()
}
function secondStep() {
gmailPage.composeClick()
}
module.exports = {
before,
after,
'1st step': firstStep,
'2nd step': secondStep
}
}());
Hope that helps you :)
Consider the following code in the official angular repository
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var testingScope = 'this is a test';
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap([], true),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function(serviceName, caller) {
if (angular.isString(caller)) {
path.push(caller);
}
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
})),
instanceCache = {},
protoInstanceInjector =
createInternalInjector(instanceCache, function(serviceName, caller) {
var provider = providerInjector.get(serviceName + providerSuffix, caller);
return instanceInjector.invoke(
provider.$get, provider, undefined, serviceName);
}),
instanceInjector = protoInstanceInjector;
providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
var runBlocks = loadModules(modulesToLoad);
instanceInjector = protoInstanceInjector.get('$injector');
instanceInjector.strictDi = strictDi;
forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
return instanceInjector;
And
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
console.log(testingScope);
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName, caller);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
return {
get: getService,
};
}
We see that createInternalInjector is able to access local variables (like path) in its caller's scope createInjector without passing in to the parameter.
Indeed if I add testingScope to createInjector and try to access in createInternalInjector, I was able to do it.
This is weird because I try to replicate this behavior like the following.
testOuter();
function testOuter() {
var outer = 'outer'
testInner().test();
}
function testInner() {
function testing() {
console.log(outer);
}
return {
test: testing
}
}
But got an error instead.
ReferenceError: outer is not defined
Can someone give me some pointers on why this is happening?
The issue here is scope chaining. createInternalInjector function is called within createInjector function, therefore it can access its parent properties. In your case you have sibling functions that are unaware to each other variables.
More on scope chains and closures: https://stackoverflow.com/a/1484230/5954939
I am having trouble figuring out how to pass the objects method rather than sort "generic prototype" method when doing callback.
function Client() {
this.name = "hello";
}
Client.prototype.apiCall = function(method, params, callback) {
callback();
}
Client.prototype.onLogin = function(error, data) {
console.log(this.name);// undefined!!!!
}
Client.prototype.start = function() {
var self = this;
self.apiCall('rtm.start', {
}, self.onLogin) // passing of method like this does not work.
}
I am passing the onLogin method but well it does not work. This is code I have re-written. Previously I nested all methods inside the Client function but well, I learned that that is not the way to do it so now I am trying using prototype.
I know there is some solution "binding" the onLogin function inside the Client() function but well I want to understand the issue.
You need to bind the apiCalls context to the callback using bind:
Client.prototype.apiCall = function(method, params, callback) {
var bound = callback.bind(this);
bound();
}
Otherwise, the this within onLogin is set to the global object.
See Call, Apply And Bind for further details.
Basically .bind(obj) returns a function which, when called, will internally use (obj) as this.
So you create this bound and then you call it.
You can use call or apply to bind this, see snippet. I've modified your code for demonstration purposes. Hope it clarifies things for you
function Client() {
this.name = "hello";
}
Client.prototype = {
apiCall: function(method, params, callback) {
try {
var trial = method.call(this, params);
callback.apply(this, [null, trial]);
} catch (e) {
callback.apply(this, [e, null]);
}
},
onLogin: function(error, data) {
if (error) {
Helpers.report('<b style="color: red">' +
'An error occured!</b> <i>' +
error.message + '</i>')
} else {
Helpers.report(this.name, ' (data.result = ' + data.result + ')');
}
},
start: function() {
Helpers.useCSS(1);
// error from this.rtm.start
Helpers.report('Command: <code>', 'this.apiCall(this.rtm.start, {will: \'not work\'}, this.onLogin);','</code>');
this.apiCall(this.rtm.start, {will: 'not work'}, this.onLogin);
// this.rtm.works is ok
Helpers.report('<br>Command: <code>',
'this.apiCall(this.rtm.works, {will: \'work\'}, this.onLogin);',
'</code>');
this.apiCall(this.rtm.works, {
will: 'work'
}, this.onLogin);
},
// --------------------------------
// added rtm for snippet demo
rtm: {
start: function(params) {
return anerror;
},
works: function(params) {
return {
result: 'worked, <code>params: ' + JSON.stringify(params) + '</code>'
};
}
},
};
new Client().start(); //<= here
<script src="https://rawgit.com/KooiInc/Helpers/master/Helpers.js"></script>
I'm running into an issue with using RequireJS and Prototypal inheritance. Here's my module:
define(function () {
function Module(data) {
this.data = data;
}
Module.prototype.getData = function () {
return this.data;
};
Module.prototype.doSomething = function () {
console.log(this.data);
console.log(this.getData());
};
return Module;
Module.prototype.callFunction = function (fn) {
if (this[fn]) {
console.log('call');
Module.prototype[fn]();
}
};
});
Then I instantiate the module, like so:
var module = new Module({ name: 'Marty' });
module.getData(); // returns { name: 'Marty' }
module.data; // returns { name: 'Marty' }
module.callFunction('doSomething') // returns undefined on the first (and second) console log
The console.logs in the module.doSomething() always return undefined. Am I misunderstanding how prototypal inheritance works with RequireJS?
As it turns out, I had written the callFunction method incorrectly. The correct way is:
Module.prototype.callFunction = function (fn) {
if (this[fn] && typeof this[fn] === "function") {
this[fn]();
}
};
The problem was using Module.prototype instead of this. Whoops.
Solution:
Yay, using this.setName() worked!
Problem:
1) Didn't know how to properly title this question
2) I am trying to call a setName() from inside of getName()
Javascript:
window.login
chat = {
setName: function( ) {
},
getName( ) {
//i want to call setName() here, is that possible?
//i tried chat.setName() and setName(), both failed.
}
}
Very simple question, I just am not too knowledgeable in JavaScript. Thank you for the suggestions/help/advice!
Use this. It refers to the current object:
chat = {
setName: function() {
alert('setName');
},
getName: function() {
this.setName();
}
};
you can use the 'this' keyword.
var chat = {
setName: function(){...},
getName: function(){ this.setName(); }
};
chat = {
setName: function( ) {
alert('test');
},
getName: function( ) {
this.setName();
}
};
chat.getName();
You have a syntax error. Try:
chat = {
setName: function() {...},
getName: function() {
chat.setName();
}
}