Passing function to other prototype - node.js

I have below code
http://jsfiddle.net/qhoc/SashU/1/
var Callback = function(op) {
this.callback = op.callback;
}
var Test = function (op) {
for (var option in op) {
if (!this[option]) this[option] = op[option];
}
}
Test.prototype.init = function(bb) {
console.log('aa = ' + this.aa);
console.log('bb = ' + bb);
if (bb < 3) {
this.init(bb + 1);
} else {
this.callback;
}
}
var finalCallback = function() {
console.log('this is finalCallback');
}
var myCallback = new Callback({
callback: finalCallback
});
var myTest = new Test({
aa: 1,
callback: myCallback
});
myTest.init(1);
Line 19 didn't print 'this is finalCallback' AT ALL because this.callback; got executed but it doesn't point to a function. But the below works:
myTest.init(1);
myCallback.callback();
I guess when passing myCallback to myTest, it didn't pass finalCallback??
Can someone help to explain this behavior and how to fix it?

seems you want to make this (use op.callback as function ):
var Callback = function (op) {
this.callback = op.callback;
return this.callback;
};
and functions should be invoked with ()
} else {
this.callback();
}
http://jsfiddle.net/oceog/SashU/3/
this is example where it can be used

this works:
var myTest = new Test({
aa: 1,
callback: myCallback.callback()
});
I assume this is the bit you mean. If not, please clarify what is not printing.
this doesn't work, because it is only a reference - an assignment.
callback: myCallback
this is what executes it ()
so:
callback: myCallback.callback;
then:
this.callback();
I apologize if I am not succinct enough. I hope I am understanding what you are asking.

As has been pointed out, you're not even trying to invoke this.callback on line 19. Invoke it with parentheses.
Even then, it doesn't work. When you do var myTest = new Test({
aa: 1,
callback: myCallback
});, myCallBack isn't a function; it's an object with a property callback. Change line 19's this.callback to this.callback.callback() to invoke that function. One line 19, this.callback is an instance of Callback—an object with a property callback that is a function.
http://jsfiddle.net/trevordixon/SashU/4/ shows a working example.

Related

"Unresolved function or method require()" when using Babel

I am studying Babel recently, and I followed the steps I found in GitHub, everything goes on the right way, I wrote some arrow function, and I get the right result, but when I tried to create class, some problems occurred, I don't know how to handle it.
problem picture
I was informed that the "unresolved function or method require()"
Does it mean I forgot to do something, First I thought maybe I need load requirejs.js, but it did work too, I search the question, but I can't find the solution, so is there someone can help me?
my code is
const square = n => n * n;
var a = 2000;
class SSPageController{
showPage(){
}
}
and the result code is
"use strict";
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var square = function square(n) {
return n * n;
};
var a = 2000;
var SSPageController = function () {
function SSPageController() {
(0, _classCallCheck3.default)(this, SSPageController);
}
(0, _createClass3.default)(SSPageController, [{
key: "showPage",
value: function showPage() {}
}]);
return SSPageController;
}();

Jasmine : Spying on a function call of another module

I have the following code structure :
const finalCall = require('./final.js');
function Func(){
this.process = {
initCall: function(params, callback){
let proParams;
//processing...
return finalCall(proParams, callback);
}
}
}
Now I need to test if my initCall function correctly processes the params and makes call to finalCall. I need to know how do I create a spy on my finalCall function, so when it gets called, I can track the proParams.
I have tried something like :
const func = new Func();
let proParams = null;
spyOn(func.process.initCall, "finalCall").and.callFake(function(pParams, callback){
proParams = pParams;
});
let params = { };
func.process.initCall(params, null);
expect(func.process.initCall.finalCall).toHaveBeenCalled();
expect(proParams).toEqual('...');
I am missing on what object I can access finalCall, or if there is another way to do so. Thanks in advance.
Finally I found a workaround to my problem. I created a prototype of the function finalCall() in my constructor Const, and put a spyOn on its object.
Solution
Main module:
const finalCall = require('./final.js');
function Func(){
const self = this;
this.process = {
initCall: function(params, callback){
let proParams;
//processing...
return self.finalCall(proParams, callback);
}
}
}
Func.prototype = finalCall;
and in my Spec file:
const func = new Func();
let proParams = null;
spyOn(const, finalCall);
let params = { };
func.process.initCall(params, null);
expect(func.finalCall).toHaveBeenCalled();

NodeJs giving me a Object #<Object> has no method

I have a class along with its helper class defined:
function ClassA(){
this.results_array = [];
this.counter = 0;
this.requestCB = function(err, response, body){
if(err){
console.log(err);
}
else{
this.counter++;
var helper = new ClassAHelper(body);
this.results_array.concat(helper.parse());
}
};
};
function ClassAHelper(body){
this._body = body;
this.result_partial_array = [];
this.parse = function(){
var temp = this.parseInfo();
this.result_partial_array.push(temp);
return this.result_partial_array;
};
this.parseInfo = function(){
var info;
//Get some info from this._body
return info
};
};
NodeJS gives me the following error:
TypeError: Object #<Object> has no method 'parseInfo'
I cannot figure out why I can't call this.parseInfo() from inside ClassAHelper's parse method.
If anyone can explain a possible solution. Or at least, what is the problem? I tried reordering the function declarations, and some other ideas, but to no avail.
P.S. I tried simplifying the code for stackoverflow. Hepefully it still makes sense :)
P.P.S This is my first stackoverflow question. Hopefully I did everything right. :)
Here's a simplified example which works:
function A() {
this.x = function (){
return this.y();
};
this.y = function (){
return "Returned from y()";
};
}
var a = new A();
a.x();
Notice the use of new and calling the method with a.x().
How are you creating an instance of your functions and calling parse in ClassAHelper?
Is it anything like these:
var a = A();
a.x();
// Or
A.x()
this is scoped to the function it is inside. So, when you do this.parse=function(){, there is a new this. To keep ClassAHelper's this, you have to pass it in or reference it inside the anonymous function you made. The following example assigns this to a variable outside of the function and references it inside the function:
function ClassAHelper(body){
this._body = body;
this.result_partial_array = [];
var self = this;
this.parse = function(){
var temp = self.parseInfo();
self.result_partial_array.push(temp);
return self.result_partial_array;
};
this.parseInfo = function(){
var info;
//Get some info from this._body
return info;
};
};
Further reading and other ways of doing it:
Why do you need to invoke an anonymous function on the same line?

Define a literal Javascript object so a property referenced directly calls a function and not its sub-ordinates [duplicate]

JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"?
This works:
var foo = function() { return 1; };
foo.baz = "qqqq";
At this point, foo() calls the function, and foo.baz has the value "qqqq".
However, if you do the property assignment part first, how do you subsequently assign a function to the variable?
var bar = { baz: "qqqq" };
What can I do now to arrange for bar.baz to have the value "qqqq" and bar() to call the function?
It's easy to be confused here, but you can't (easily or clearly or as far as I know) do what you want. Hopefully this will help clear things up.
First, every object in Javascript inherits from the Object object.
//these do the same thing
var foo = new Object();
var bar = {};
Second, functions ARE objects in Javascript. Specifically, they're a Function object. The Function object inherits from the Object object. Checkout the Function constructor
var foo = new Function();
var bar = function(){};
function baz(){};
Once you declare a variable to be an "Object" you can't (easily or clearly or as far as I know) convert it to a Function object. You'd need to declare a new Object of type Function (with the function constructor, assigning a variable an anonymous function etc.), and copy over any properties of methods from your old object.
Finally, anticipating a possible question, even once something is declared as a function, you can't (as far as I know) change the functionBody/source.
There doesn't appear to be a standard way to do it, but this works.
WHY however, is the question.
function functionize( obj , func )
{
out = func;
for( i in obj ){ out[i] = obj[i]; } ;
return out;
}
x = { a: 1, b: 2 };
x = functionize( x , function(){ return "hello world"; } );
x() ==> "hello world"
There is simply no other way to acheive this,
doing
x={}
x()
WILL return a "type error". because "x" is an "object" and you can't change it. its about as sensible as trying to do
x = 1
x[50] = 5
print x[50]
it won't work. 1 is an integer. integers don't have array methods. you can't make it.
Object types are functions and an object itself is a function instantiation.
alert([Array, Boolean, Date, Function, Number, Object, RegExp, String].join('\n\n'))
displays (in FireFox):
function Array() {
[native code]
}
function Boolean() {
[native code]
}
function Date() {
[native code]
}
function Function() {
[native code]
}
function Number() {
[native code]
}
function Object() {
[native code]
}
function RegExp() {
[native code]
}
function String() {
[native code]
}
In particular, note a Function object, function Function() { [native code] }, is defined as a recurrence relation (a recursive definition using itself).
Also, note that the answer 124402#124402 is incomplete regarding 1[50]=5. This DOES assign a property to a Number object and IS valid Javascript. Observe,
alert([
[].prop="a",
true.sna="fu",
(new Date()).tar="fu",
function(){}.fu="bar",
123[40]=4,
{}.forty=2,
/(?:)/.forty2="life",
"abc".def="ghi"
].join("\t"))
displays
a fu fu bar 4 2 life ghi
interpreting and executing correctly according to Javascript's "Rules of Engagement".
Of course there is always a wrinkle and manifest by =. An object is often "short-circuited" to its value instead of a full fledged entity when assigned to a variable. This is an issue with Boolean objects and boolean values.
Explicit object identification resolves this issue.
x=new Number(1); x[50]=5; alert(x[50]);
"Overloading" is quite a legitimate Javascript exercise and explicitly endorsed with mechanisms like prototyping though code obfuscation can be a hazard.
Final note:
alert( 123 . x = "not" );
alert( (123). x = "Yes!" ); /* ()'s elevate to full object status */
Use a temporary variable:
var xxx = function()...
then copy all the properties from the original object:
for (var p in bar) { xxx[p] = bar[p]; }
finally reassign the new function with the old properties to the original variable:
bar = xxx;
var A = function(foo) {
var B = function() {
return A.prototype.constructor.apply(B, arguments);
};
B.prototype = A.prototype;
return B;
};
NB: Post written in the style of how I solved the issue. I'm not 100% sure it is usable in the OP's case.
I found this post while looking for a way to convert objects created on the server and delivered to the client by JSON / ajax.
Which effectively left me in the same situation as the OP, an object that I wanted to be convert into a function so as to be able to create instances of it on the client.
In the end I came up with this, which is working (so far at least):
var parentObj = {}
parentObj.createFunc = function (model)
{
// allow it to be instantiated
parentObj[model._type] = function()
{
return (function (model)
{
// jQuery used to clone the model
var that = $.extend(true, null, model);
return that;
})(model);
}
}
Which can then be used like:
var data = { _type: "Example", foo: "bar" };
parentObject.createFunc(data);
var instance = new parentObject.Example();
In my case I actually wanted to have functions associated with the resulting object instances, and also be able to pass in parameters at the time of instantiating it.
So my code was:
var parentObj = {};
// base model contains client only stuff
parentObj.baseModel =
{
parameter1: null,
parameter2: null,
parameterN: null,
func1: function ()
{
return this.parameter2;
},
func2: function (inParams)
{
return this._variable2;
}
}
// create a troop type
parentObj.createModel = function (data)
{
var model = $.extend({}, parentObj.baseModel, data);
// allow it to be instantiated
parentObj[model._type] = function(parameter1, parameter2, parameterN)
{
return (function (model)
{
var that = $.extend(true, null, model);
that.parameter1 = parameter1;
that.parameter2 = parameter2;
that.parameterN = parameterN;
return that;
})(model);
}
}
And was called thus:
// models received from an AJAX call
var models = [
{ _type="Foo", _variable1: "FooVal", _variable2: "FooVal" },
{ _type="Bar", _variable1: "BarVal", _variable2: "BarVal" },
{ _type="FooBar", _variable1: "FooBarVal", _variable2: "FooBarVal" }
];
for(var i = 0; i < models.length; i++)
{
parentObj.createFunc(models[i]);
}
And then they can be used:
var test1 = new parentObj.Foo(1,2,3);
var test2 = new parentObj.Bar("a","b","c");
var test3 = new parentObj.FooBar("x","y","z");
// test1.parameter1 == 1
// test1._variable1 == "FooVal"
// test1.func1() == 2
// test2.parameter2 == "a"
// test2._variable2 == "BarVal"
// test2.func2() == "BarVal"
// etc
Here's easiest way to do this that I've found:
let bar = { baz: "qqqq" };
bar = Object.assign(() => console.log("do something"), bar)
This uses Object.assign to concisely make copies of all the the properties of bar onto a function.
Alternatively you could use some proxy magic.
JavaScript allows functions to be
treated as objects--you can add a
property to a function. How do you do
the reverse, and add a function to an
object?
You appear to be a bit confused. Functions, in JavaScript, are objects. And variables are variable. You wouldn't expect this to work:
var three = 3;
three = 4;
assert(three === 3);
...so why would you expect that assigning a function to your variable would somehow preserve its previous value? Perhaps some annotations will clarify things for you:
// assigns an anonymous function to the variable "foo"
var foo = function() { return 1; };
// assigns a string to the property "baz" on the object
// referenced by "foo" (which, in this case, happens to be a function)
foo.baz = "qqqq";
var bar = {
baz: "qqqq",
runFunc: function() {
return 1;
}
};
alert(bar.baz); // should produce qqqq
alert(bar.runFunc()); // should produce 1
I think you're looking for this.
can also be written like this:
function Bar() {
this.baz = "qqqq";
this.runFunc = function() {
return 1;
}
}
nBar = new Bar();
alert(nBar.baz); // should produce qqqq
alert(nBar.runFunc()); // should produce 1

node.js - why this local function can modify global variables?

Here is my code:
var handleCondition = function(condition,params){
var dup_condition;
dup_condition = condition;
var isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
var __replace = function(str){
var reg_slot = /^#(.+)/;
if(reg_slot.test(str) == true){
var ss = reg_slot.exec(str)[1];
return params[ss];
}else{
return str;
}
};
var compare = function(a){
var arr = a;
if(params != undefined){
for(var j =1;j<arr.length;j++){
arr[j] = __replace(arr[j]);
}
}
switch(arr[0]){
case "$eq":
case "==":
return (arr[1] == arr[2]);
default:
return (arr[1] == arr[2]);
}
};
if(isArray(dup_condition)){
var im = function (arr){
for(var i=0;i<3;i++){
if(isArray(arr[i])){
arr[i] = im(arr[i]);
}
}
return compare(arr);
};
var res = im(dup_condition);
return res;
}
};
/*Here are test data*/
var c = {
"beforeDNS":
["$eq","#host",["$eq",10,10]]
,
"afterDNS":["$match",/^10\.+/,"#ip"]
};
var params ={
host:"dd"
};
console.log(c["beforeDNS"]); // ==> ["$eq","#host",["$eq",10,10]]
handleCondition(c["beforeDNS"],params);
console.log(c["beforeDNS"]); // ==> ["$eq","dd",true]
handleCondition(c["beforeDNS"],params);
The first time I run the code with the expected result;
However , when I tried to run the function second time,to my surprise,the value of c["beforeDNS"] has changed unexpectedly!
In fact,I haven't write any code in my function to modify the value of this global variable,but it just changed.
So please help me find the reason of this mysterious result or just fix it.Thanks!
Your dup_condition variable isn't duping anything. It's just a reference to the argument you pass in.
Thus when you pass it to the im function, which modifies its argument in place, it is just referencing and modifying condition (which is itself a reference to the c["beforeDNS"] defined outside the function).
To fix this you might use slice or some more sophisticated method to actually dupe the arguments. slice, for example, would return a new array. Note though that this is only a shallow copy. References within that array would still refer to the same objects.
For example:
if (isArray(condition)) {
var dup_condition = condition.slice();
// ...
}
In javascript the objects are passed by reference. In other words, in handleCondition dup_condition still points to the same array. So, if you change it there you are actually changing the passed object. Here is a short example which illustrates the same thing:
var globalData = {
arr: [10, 20]
};
var handleData = function(data) {
var privateData = data;
privateData.arr.shift();
privateData.arr.push(30);
}
console.log(globalData.arr);
handleData(globalData);
console.log(globalData.arr);
The result of the script is:
[10, 20]
[20, 30]
http://jsfiddle.net/3BK4b/

Resources