Ques - Write partial function in javascript. Here is the expected behavior of that function -
function add(param1,param2){
return param1 + param2;
}
add.apply(null,[5,4]); // returns 9
now modify the add function so that we can pass the parameter 1 by 1, i.e.-
add(5)(4) ; // 9
Ans -
function add(x,y){
if(typeof(x) === 'undefined'){
return function(y){
return x+y;
}
}
return x + y;
}
Ques - Write a function namespace() which can create a namespace hierarchy for you-
MYAPP.namspace('module1,module2,module3'); should create a namespace named as MYAPP.module1.module2.module3.
Ans -
Generally we can directly create namespace like this -
MYAPP = {};
the issue is, whats if this name was already exist, then by writing this statement, we will override the existing function. So here is the right statement -
MYAPP = MYAPP || {};
Here is small code which creates a namespace -
namespace = function (ns_string){
var parts = ns_string.split('.');
var root = {};
if(parts.length>0){
root = this[parts[0]] || this;
}
for(var i=0;i
root[parts[i]] = {};
}
root = root[parts[i]];
}
return root;
}
namespace('global.MSSB.WebFramework.Coreservice');
alert(global.MSSB.WebFramework.Coreservice);
Ques - What will be the output of following function-
var myvar = function() {
alert('my old var');
myvar= function() {
alert('my new var');
}
}
var anotherVar = myvar;
anotherVar(); // --1
anotherVar();// --2
myvar();// --3
myvar();// --4
anotherVar();// --5
anotherVar();// --6
Ans -myvar defines a function, which while execution define the myvar again, and thus overrides the original definition of myvar. But while assignment of myvar to myanotherVar, the old definition only gets copied, and every time the old function get executed. Lets understand it by looking at the output -
(1) - my old var
(2) - my old var
(3) - my new var
(4) - my new var
(5) - my old var
(6) - my old var
If you check, anotherVar alerts the old definition whereas myvar alerts the new definition, because once the myvar got executed, its original definition got overwritten by the new definition.
No comments:
Post a Comment