I need function change to change variables and return back to Tst1. I expect to get in console:
5
aaa
but have unchanged ones:
6
bbb
My functions:
function change ( aa,bb )
{
aa=5;
bb="aaa";
}
function Tst1()
{
aa=6;
bb="bbb";
change(aa,bb);
console.log (aa);
console.log (bb);
}
One way is to move change() into the function test(). Then it shares the same variables as the calling scope.
'use strict';
function test() {
function change() {
aa = 6;
bb = 76;
}
var aa = 5,
bb = 6;
change();
document.write(aa + " " + bb);
}
test();
JavaScript is like java in that primitives are never passed by reference but objects are always passed by reference. You need to wrap your data in an object and pass that instead:
function change (aa, bb)
{
aa.value = 5;
bb.value = "aaa";
}
function Tst1()
{
aa = { value: 6 };
bb = { value: "bbb" };
change(aa, bb);
console.log (aa.value); // outputs 5
console.log (bb.value); // outputs aaa
}
or you can play with global variable, but it is not a good practice.
var aa,bb;
function change(){
aa=6;
bb=76;
}
function test(){
aa = 5;
bb = 6;
change();
console.log(aa + " " + bb);
}
test();
Short answer: NO, you can't pass primitive parameters by reference in JS.
One alternative solution to the presented here is to return the result values as array of items:
function change ( aa,bb )
{
aa=5;
bb="aaa";
return [aa, bb];
}
function Tst1()
{
aa=6;
bb="bbb";
result = change(aa,bb);
aa = result[0];
bb = result[1];
document.writeln(aa);
document.writeln(bb);
}
Tst1();
Related
Really new to Javascript. This code is taken from MDN.
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var s = sum(1);
var s1 = s(2);
var s2 = s1(3);
var s3 = s2(4);
console.log(s3) //log 20
When I try to input different variable names (EX below) they don't seem to work and I don't understand how everything links up together to spit out the answer 20.
// global scope
var e = 10;
function sum(a){
return function sum2(b){
return function sum3(c){
// outer functions scope
return function sum4(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var w = sum(1);
var x = s(2);
var y = s1(3);
var z = s2(4);
console.log(s3) //log 20
When I change it to this it also does not work. The console tells me that sa is not defined
// global scope
var e = 10;
function sm(a){
return function sa(b){
return function sb(c){
// outer functions scope
return function sc(d){
// local scope
return a + b + c + d + e;
}
}
}
}
var s = sm(1);
var s1 = sa(2);
var s2 = sb(3);
var s3 = sc(4);
console.log(sc) //log 20
I can keep throwing out more examples that don't work. Someone, please help me understand how the first example works.
function sm(a){
return function sa(b){
return function sb(c){
// outer functions scope
return function sc(d){
// local scope
return a + b + c + d + e;
}
}
}
}
The function sm is taking one argument and is returning a function which takes one argument. The function sm returns is not named sb. Try to think of it as the return value of sm .
So, when you do
var s = sm(1);
The returned function is stored in the variable s
Now if you want to run the second function (sa inside sm) you need to invoke s.
var s1 = s(2);
The returned function (sb) is stored inside varibale s1.
Similarly,
var s2 = s1(3);
var s3 = s2(4);
console.log(s3); // 20
I've been my banging head against the wall with the above question. Let's say I have the following class:
function Counter() {...}
so when I call the constructor:
var c= new Counter();
console.log(c); //return 0
furthermore If I created the following method:
Counter.prototype.increment = function() {
return this += 1;
};
it should increment c by 1 for every call
c.increment(); // return c=1
c.increment(); // return c=2
so far I have come up with:
function Counter(){return Number(0)}
but still returns Number{} not a zero...
Any thoughts?
Thanks in advance!
JavaScript doesn't allow for a custom Object type to directly imitate a primitive value. It also doesn't allow this to be assigned a new value.
You'll have to instead store the value within a property:
function Counter() {
this.value = 0;
}
var c = new Counter();
console.log(c); // Counter { value: 0 }
And, increment the value from it:
Counter.prototype.increment = function () {
this.value += 1;
};
c.increment();
console.log(c.value); // 1
Though, you can at least specify how the object should be converted to a primitive with a custom valueOf() method:
Counter.prototype.valueOf = function () {
return this.value;
};
console.log(c.value); // 1
console.log(c + 2); // 3
You can't return a value from the constructor because you instantiate it using the new keyword, this gives you a new instance of the object.
Store a property and increment that instead:
function Counter() {
this.count = 0;
}
Counter.prototype.increment = function() {
this.count++;
return this.count;
};
var c= new Counter();
console.log( c.increment() ); // 1
console.log( c.increment() ); // 2
console.log( c.increment() ); // 3
This is your problem:
Counter.prototype.increment = function() {
return this += 1;
};
this is an object, += is not defined for objects.
I'm new on Javascript. I'm trying to do this exercise, but i cannot found anything to help me with that.
I created this object
var Foo = function(value) {
this.val = value;
}
And now I need sum two Foo objects with + operator.
var first = new Foo(2);
var second = new Foo(3);
var result = first + second; //should be 5
Do I have a way to overload operator + (like c++) , declare my Foo object as an Integer or something like that?
var result = first.val + second.val;
alert(result); // 5
jsfiddle: http://jsfiddle.net/czhE3/
UPD
OK, without val:
var Foo = function(value) {
this.val = value;
this.toString = function() {
return this.val;
}
}
var first = new Foo(2);
var second = new Foo(3);
var result = first + second;
alert(result); // 5
http://jsfiddle.net/czhE3/1/
As the previous people have mentioned you cannot override operators in javascript, but you could implement a valueOf which is the arithmetic version of a toString().
Add the follow code line:
Foo.prototype.valueOf = function () { return this.val; };
or
this.valueOf = function () { return this.val; };
Working fiddle http://jsfiddle.net/fJJL9/
There is no way in Javascript to overload operators as in C++. The closest thing you can make is a sum function for your objects, like
function sum ( a, b ) { return a.value + b.value; }
This is similar to two other questions I've asked today, but I'm still trying to understand how to assign variables correctly in JavaScript.
The output to my code is this:
x: 3
x: undefined // I was expecting 3 here
And here's my code:
var myApplication = {};
(function() {
function beep(x) {
console.log('x: ' + x);
var closure = {};
return function() {
console.log('return function() {');
if (arguments.length) {
console.log('setter: ' + x);
closure.result = x;
} else {
console.log('getter: ' + closure.result);
return closure.result;
}
}
}
myApplication.beep = beep;
})();
myApplication.beep(3);
RESULT = myApplication.beep();
I think the problem is where I say: myApplication.beep = beep;
I think that I've got to assign it either via the prototype or some other way.
First of all, functions are first class citizens in javascript.
So when you do
return function() {
console.log('return function() {');
if (arguments.length) {
console.log('setter: ' + x);
closure.result = x;
} else {
console.log('getter: ' + closure.result);
return closure.result;
}
}
This function is not executed, you are only returning as the value of your beep function.
So, in our case, the only code that really gets executed is :
var myApplication = {};
(function() {
function beep(x) {
console.log('x: ' + x);
}
myApplication.beep = beep;
})();
myApplication.beep(3);
RESULT = myApplication.beep();
In this case you are only logging the first argument passed to beep, so 3 then undefined.
Now for what you want to do here, no need to use closures, or prototypes :
var myApplication = {
x : null,
beep : function (x) {
if (typeof x != 'undefined') {
this.x = x;
} else {
return this.x;
}
}
};
// set x
myApplication.beep(3);
// get x
var x = myApplication.beep();
console.log('x :', x);
I would avoid messing with closures too early.
When you call beep(3) the first time, it's returning a function - but you aren't actually doing anything with that function. I think you might have meant this on the second-to-last line?...:
myApplication.beep = myApplication.beep(3);
As it is, I think the second call to beep is just returning another function, but with its 'x' argument set to undefined.
Also: To save some code-writing, rather than declaring and then assigning 'beep', you could write this:
myApplication.beep = function(x) { ...
Or, the whole object can be declared at once from the beginning:
myApplication = {
beep: function(x) {
},
otherFn: function(y) {
}
}
Suppose we define a function that simply increments its input by some stored value dd:
var obj={}
obj.dd=1
obj.f=function(x){
return x+this.dd
}
Alternatively you could create a closure for dd as follows but this would create a static increment as opposed to one that could be altered later:
var dd=1
var f=function(x){
return x+dd
}
We could alternatively store dd in the function itself:
var obj={}
obj.f=function(x){
return x+this.f.dd
}
obj.f.dd=1
I am curious as to whether it is possible for a function to retrieve a variable attached to itself without going through a parent object, something like a self keyword that would refer to the function itself and would allow the following:
var f=function(x){
return x+self.dd
}
f.dd=1
I know it is unnecessary to do such a thing but I think it would be cool if you could.
You can give function literals a name:
var f = function me(x) {
return x + me.dd;
};
f.dd = 1;
This doesn’t work properly in older versions of IE/JScript, though, as me and f don’t reference the same object. The (deprecated and not usable in strict mode) alternative is arguments.callee:
var f = function(x) {
return x + arguments.callee.dd;
};
f.dd = 1;
Also, your note about the closure isn’t quite right; it can be altered later, even through another function:
var dd = 1;
var f = function(x) {
return x + dd;
};
var setdd = function(_dd) {
dd = _dd;
};
A function is an object. If you reference the var holding the function:
var f = function (x) {
return x + f.dd
};
f.dd = 1;
alert(f(1));
result: 2
If the function is named, you can do the same:
function foo(x) {
return x + foo.dd;
}
foo.dd = 1;
alert(foo(1));
result: 2