Reputation: 29
How can I create a function where it gets it's property?
For example:
myfunc = function(){
alert(this.a + ":" + this.b);
};
myfunc.a = 5;
myfunc.b = 6;
The results is 5:6
Upvotes: 0
Views: 84
Reputation: 392
Try this:
myfunc = function(){
alert(this.a + ":" + this.b);
};
myfunc.call({a: 5, b: 6});
When you use the call function, the first parameter is your function's this
and the second parameter is your function. The call
function just call you function and assign {a: 5, b: 6}
to myfunc
's this.
Upvotes: 0
Reputation: 3102
There are two ways. The first, is as others have mentioned is to name the parameters in your function delcaration:
function foo(a, b) {
alert(a + ':' + b);
}
foo('hello', 'world'); // Output "hello:world"
Another way however is that a variable is available which contains all function parameters, called arguments
.
function bar() {
alert(arguments[0] + ':' + arguments[1]);
}
bar('hello', 'world'); // Output "hello:world"
It should be noted that while it looks like an array, the arguments
variable is not an instance of the JavaScript Array
object, the only Array
property available to use with arguments
is .length
.
Upvotes: 1
Reputation: 6366
This could be done with a closure:
var myFunc = (function(a, b) {
return function() {
console.log(a + ":" + b);
}
})(5, 6)
myFunc();
This can be expanded via prototype
to create class like behaviour:
var myFunc = (function () {
function myFunc(a, b) {
if (a === void 0) { a = 5; }
if (b === void 0) { b = 6; }
this.a = a;
this.b = b;
}
myFunc.prototype.log = function () {
console.log(this.a + ":" + this.b);
};
return myFunc;
}());
var a = new myFunc();
a.log();
new myFunc().log();
new myFunc(1, 10).log();
//ACCESS ATTRIBUTE
console.log("ACCESSING", a.a);
//OVERWRITE ATTRIBUTE
a.a = 11;
//ACCESS ATTRIBUTE
console.log("ACCESSING", a.a);
a.log();
Upvotes: 0