I am trying to get the function in a function with argument inside the child function
function firstF (){
this.childF1 = function($argument){
// do something + $argument
}
this.childF2 = function($argument2){
// do something + $argument2
}
}
//Declare a new firstF
var firstFunction = new firstF();
firstFunction.childF1
how do i declare the $argument here?
You do it like this:
var firstFunction = new firstF();
firstFunction.childF1(arghere)
childF1 is a property of your firstF object and that property is a function. So, you call it like a function with parens and you pass the arguments in the parens. You must call it on an already created object of type firstF, not on the firstF function itself.
Related
I want to do something like this:
var f = function(){
var args = arguments;
args.push(this._caller);
this._base(args);
};
f._caller = someObject;
f._base = function(x,y,z){ alert(x+':'+y+':'+z);};
f(y,z);
Basically - I want to give function some inner parameters, but still function should be called with its parameters and user should not know about this parameters when he calls this function.
Problem is, that in the function body 'this' will mean 'Window' and not the function in need.
So how can I do this? And can I do this at all?
this won't be the function itself, but the context the function was called with. You can access properties of the function if you name it (var f does not set the name).
var f = function fn() {
var _caller = fn._caller;
var _base = fn._base;
// ...
};
The method arguments.push() doesn't exist as arguments isn't actually an Array. Though, you can create an Array from it with .slice():
var args = Array.prototype.slice.call(argument, 0);
args.push(_caller);
To set the context (this) and pass an Array of arguments, use Function#apply.
return _base.apply(this, args);
function shortUrl () {
$['post']('http://tinyurl.com/api-create.php?url=http://json-tinyurl.appspot.com/', function (a) {
});
};
I Want to make this function as a var so I can use shortUrl Anywhere in my script. Like
var shortaddress = shortUrl ();
I want to use the result in next function.
function shortUrl () {...}
is equivalent to
var shortUrl = function () {...};
So, it is already a variable.
A function is already a variable, so you can use it as such. For instance:
function foo() {
// ...
};
is more or less the same as
var foo = function() {
// ...
};
Basically, if you drop the parentheses and arguments (foo instead of foo()), you can use any function as a normal variable.
Therefore you can for instance assign it to other variables, like you normally would:
var bar = foo; // note: no parentheses
bar(); // is now the same as foo()
Or you can pass it as an argument to another function:
function callFunc(func) {
func(); // call the variable 'func' as a function
}
callFunc(foo); // pass the foo function to another function
If you want to use the shortUrl function anywhere, it must be declared in global scope. Then that variable becomes a property of Window object. For example the following variables
<script type="text/javascript">
var i = 123;
function showA(){ alert('it'); window.j = 456; }
var showB = function() { alert('works'); var k = 789; this.L = 10; }
</script>
are declared directly in Window object and so become its attributes. Thus now they can be easily accessed from any script. For example all the following commands work:
<script type="text/javascript">
alert(i); alert(window.i);
showA(); window.showA();
showB(); window.showB();
alert(j); alert(window.j);
alert(new showB().L); // here the function was called as constructor to create a new object
</script>
Functions in javascript are objects and so they can hold attributes in themselves.
In the example above you can consider the k variable to be a private property and the L variable a public property of the showB object(or function). And another example: if you include jQuery library in your page, jQuery usually exposes itself as window.jQuery or window.$ object. Just it's generally recommended to use global variables very sparely and carefuly to prevent possible conflicts.
How can i call a YUI function that is wrapped inside a YUI().use from javascript?
example
Below is a YUI function "runShowAnim" which executes animShow.run(); for an animation effect...
var runShowAnim = function(e) {
animShow.run();
};
I want this effect to happen when i validate something in a javascript function. I tried to call it as below. But it doesn't seem to work.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
I achieved this by sandwiching the YUI function completely inside a function and calling that function..
var runShowAnim = function() {
YUI().use('anim', 'node', function(Y) {
var animShow = new Y.Anim({
node: '#msgArea',
to: { height: 50,opacity:1 }
});
animShow.run();
});
};
now i can call runShowAnim without any problem like in the below sample function..
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
If you want to call a function, you have to suffix the function name with () and include 0 or more comma separated arguments between them.
runShowAnim();
If the function doesn't have global scope (as yours will have if it is declared inside a function passed to use()) and not passed outside in some way then you can only do this from the same scope.
I think you're missing the parentheses.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim(); // right here
}
YUI.thefunction()?
I think you need to call it with namespace too
something similar to
var X = function(){};
X.Y = function(){};
X.Y.Z = function(){};
X.Y.Z.foo = function(e){alert(e);}
//foo("me");<-error
X.Y.Z.foo("me");
If you want to call a function that has been defined inside the closure (the function passed as the last parameter to YUI.use) from outside it, you need to expose the function globally.
Either define a global variable outside the closure and assign your function to it, or assign your function to the window object
i.e.
var runShowAnim;
YUI().use(function(e){
runShowAnim = function(){alert('called');}
});
runShowAnim();
I am trying to pass variable though the GetDetail function below. I can pass string/number and it works properly.
But I'm unable to pass variable
detLink.onclick = new Function ("GetDetails()");
detLink.setAttribute('onclick',"javascript:GetDetails()")
detLink.onclick = function () { GetDetails ( parameter1, parameter2, ... ); }
which is an anonymous function.
Read also The function expression (function operator)
A function expression is similar to and has the same syntax as a function declaration
function [name]([param] [, param] [..., param]) {
statements
}
name
The function name. Can be omitted, in which case the function becomes
known as an anonymous function.
param
The name of an argument to be passed to the function. A function can
have up to 255 arguments.
statements
The statements which comprise the body of the function.
detLink.setAttribute('onclick',"javascript:GetDetails("+yourVariableName+")")
When You set attribute You are using string datatype, thus you have to stitch function name with variable VALUE
If you have access to the variable in question when you set the click handler,
detLink.onclick = function() {
GetDetails(foo);
}
If you don't,
detLink.id = uniqueId;
detLink.onclick = function() {
var foo = globalData[this.id];
GetDetails(foo);
}
// somewhere else in your code, where you know the value of the variable
globalData[detLink.id] = foo;
var val1 = "Hell world"
detLink.onclick = GetDetails( val1 );
function GetDetails( myVar ){
alert ( myVar );
}
I have a javascript function (class) that takes a function reference as one paremter.
function MyClass ( callBack ) {
if (typeof callBack !== 'function')
throw "You didn't pass me a function!"
}
For reasons I won't go in to here, I need to append something to the function by enclosing it in an anonymous function, but the only way I've been able to figure out how to do it is by adding a public function to MyClass that takes the callBack function as a parameter and returns the modified version.
function MyClass () {
this.modifyCallBack = function ( callBack ) {
var oldCallBack = callBack;
callBack = function () {
oldCallBack(); // call the original functionality
/* new code goes here */
}
return callBack;
}
}
/* elsewhere on the page, after the class is instantiated and the callback function defined */
myCallBackFunction = MyClassInstance.modifyCallBack( myCallBackFunction );
Is it possible to make this work when passing the callBack function as a parameter to the class? Attempting to modify the function in this manner when passign it as a parameter seems to only affect the instance of it in within the class, but that doesn't seem like it's a valid assumption since functions are Objects in javascript, and are hence passed by reference.
Update: as crescentfresh pointed out (and I failed to explain well), I want to modify the callBack function in-place. I'd rather not call a second function if it's possible to do all of this when the class is instantiated.
Function objects don't provide methods to modify them. Therefore, what you want to do is impossible the way you want to do it. It's the same thing Jon Skeet likes to point out about Java: Objects are not really passed by reference, but instead a pointer to them is passed by value. That means that changing the value of an argument variable to a new one won't affect the original one at all.
There are only two ways to do what you want in call-by-value languages like Java and JavaScript: The first one would be to use the (function) object's methods to modify it. As I already stated, function objects don't have those. The other one is to pass the object of which the function object is a property as a second argument and set the appropriate property to a new function which wraps the old one.
Example:
var foo = {};
foo.func = function() {};
function wrapFunc(obj) {
var oldFunc = obj.func;
obj.func = function() {
// do some stuff
oldFunc.call(obj, _some_argument__);
};
}
wrapFunc(foo);
This works for global functions as well: they are properties of the window object.
As Javascript uses lexical scoping on variables the following is possible:
var modifiableCallback=function() { alert('A'); };
function ModifyCallbackClass(callback)
{
modifiableCallback=function() { callback(); alert('B'); };
}
function body_onload()
{
var myClass=new ModifyCallbackClass(modifiableCallback);
modifiableCallback();
}
This does what you want, however the function "modifiableCallback" must be referred to with the same name inside ModifyCallbackClass, otherwise the closure will not be applied. So this may limit the usefulness of this approach for you a little.
Using eval (performance may suffer a bit) it is also possible to make this approach more flexible:
var modfiableCallback1=function() { alert('A'); };
var modfiableCallback2=function() { alert('B'); };
var modfiableCallback3=function() { alert('C'); };
function ModifyCallbackClass(callbackName)
{
var temp=eval(callbackName);
var temp2=eval(callbackName);
temp= function() { temp2(); alert('Modified'); };
eval(callbackName + " = temp;");
}
function body_onload()
{
var myClass=new ModifyCallbackClass("modfiableCallback1");
modfiableCallback1();
myClass=new ModifyCallbackClass("modfiableCallback2");
modfiableCallback2();
myClass=new ModifyCallbackClass("modfiableCallback3");
modfiableCallback3();
}
I assume you are saving this callback somewhere... Any reason this won't work?
function MyClass ( callBack ) {
var myCallBack;
if (typeof callBack !== 'function')
throw "You didn't pass me a function!"
var oldCallBack = callBack;
callBack = function () {
oldCallBack(); // call the original functionality
/* new code goes here */
}
myCallBack = callback;
}
You want to do something like:
function MyClass () {
this.modifyCallBack = function ( callBack ) {
var oldCallBack = callBack;
callBack = function () {
oldCallBack(); // call the original functionality
alert("new functionality");
}
return callBack;
}
}
/* elsewhere on the page, after the class is instantiated and the callback function defined */
var myCallBackFunction = function () {alert("original");};
var MyClassInstance = new MyClass();
myCallBackFunction = MyClassInstance.modifyCallBack( myCallBackFunction );
myCallBackFunction();