function Cons()
{
this.a = "variable a";
this.callme = function callme()
{
var str = "";
for(var x in this)
{
str += this[x] + " ";
}
return str;
}
}
var obj = new Cons();
obj.c = "variable 2";
var fin = obj.callme();
document.write(fin);
I want to have a function inside the object so that when it is called it can return a string consisting of the values of every member. Here in this case a and c. Now what happens, everything inside the function i mean the code is printed inside the browser instead of just returning the value of str.
What i understood is that this["callme"] part in the for-in loop returns the whole code as its also a variable. So how to solve this problem.
I am new to javascript please help me.
There are several ways to solve this:
1) Remove callme from the for..in :
for(var x in this) {
if (x !== 'callme') {
str += this[x] + " ";
}
}
2) Declare callme as a non-enumerable property:
function Cons() {
Object.defineProperty('callme', {
enumerable : false,
value : function callme() {
var str = "";
for(var x in this)
{
str += this[x] + " ";
}
return str;
}
});
}
3) Change the toString method of callme to return nothing:
function Cons() {
this.a = "variable a";
this.callme = function callme() {
var str = "";
for(var x in this)
{
str += this[x] + " ";
}
return str;
}
this.callme.toString = function(){ return '';};
}
The simplest solution is the first one, but the others are too interesting to pass.
If you want to avoid the function body being printed, check if the property is a function and print only its name:
this.callme = function callme()
{
var str = "";
for(var x in this)
{
if ('function' === typeof this[x]) {
str += x + " ";
} else {
str += this[x] + " ";
}
}
return str;
}
Related
I don't understand how to solve the following problem when return the value from nested function. is it wrong method. How can I get it?
My basic purpose is to get array values (all coordinates) from var mymap_coordinates, but it can't. that's why I use .toString() to test.
*<script>
mymap.on( //leftlet code
'contextmenu',
function (event)
{
var tg_marker = L.marker(event.latlng, {icon: treegroupIcon}).addTo(mymap);
store_coordinates[incre_coord] = new Point(tg_marker.getLatLng().lat.toFixed(8), tg_marker.getLatLng().lng.toFixed(8));
var n = store_coordinates.length;
var mymap_coordinates = abcdefg(store_coordinates, n);
window.alert (mymap_coordinates.toString()); //This alert can't print all array value when return the value from abcdefg function
incre_coord = incre_coord + 1;
}
);
function abcdefg(points, n)
{
.......
.......
.......
// return Result
var num = 0;
var map_coordinate = new Array();
for (let temp of abc.values())
{
map_coordinate[num] = "[" + temp.x + ", " + temp.y + "]";
num = num + 1;
}
window.alert (map_coordinate.toString()); //This alert can print all array value
return map_coordinate;
}
</script>*
In what way could I make the function return 3 values to me so that those 3 values would serve as input parameters for another function (as if it were a callback --which in fact, I think it is--)?
Until now, try the following (although it did not work):
var resultado;
function num_2(repet){
for (var i = 0; i > repet-1; i++) {
if (i>=1) {
return i + ", ";
}else{
return i;
}
}
}
function sumarr(a,b,c){
if (a!="" && a!=null) {
resultado = a+b+c;
return "\n" + "resul: " + resultado + '\n' + "1: " +
a + '\n' + "2: " + b + '\n' + "3: " + c + '\n' + '\n';
}else{
return "noting";
}
}
console.log("\n" + "callback 2: " + sumarr(num_2(3)));
You can return an array from the first function and pass each element to another other function as independent argument using Spread Operator.
var resultado;
function num_2(repet){
return [...Array(repet)].map((x,i) => i)
}
function sumarr(a,b,c){
return a + b + c
}
console.log("\n" + "callback 2: " + sumarr(...num_2(3)))
If its hard for you to understand the first function so its same as
function num_2(repet){
let res = [];
for(let i = 0;i<repet;i++){
res.push(i)
}
return res;
}
You have two options; return a JSON object, return an array.
Returning a JSON object you can name the properties then modify the second function to accept the object and access the properties;
var input = function() {
return {
a: 1,
b: 2
};
}
var output = function(obj) {
console.log(obj.a);
console.log(obj.b);
}
output(input());
Returning an array and using that as the arguments to call the function with apply() or with spread syntax
var input = function() {
return [1, 2];
}
var output = function(a, b) {
console.log(a);
console.log(b);
}
output.apply(this, input());
output(...input());
These all have the same result printing the following in the console;
1
2
with JS object :
var Vals = Return3Values();
console.log( Vals.a, Vals.b, Vals.c );
function Return3Values()
{
return {a:5, b:'hello', c:15 }
}
If you are able to use the latest JS features, you can use Destructuring Assignment in your functions to solve this and clean up your code.
function logLotsOfThings({thing1, thing2, thing3}) {
console.log(thing1, thing2, thing3)
}
function getLotsOfThings() {
return {
thing1: "I am thing 1",
thing2: "I am thing 2",
thing3: "I am thing 3"
}
}
logLotsOfThings(getLotsOfThings())
I've just asked this question (multiple errors while momoizing function inside another function) and I've got a nice answer... but! Just to understand a little more about JavaScript, I'd like to know if the momoized function can be written in this style:
function main () {
function memoized_f(){
//memoizing code
}
}
EDIT: Please notice I'm not asking what is the difference in the code above, I'm asking if it is possible to memoize the second one!
So, how to rewrite this?
function main() {
var create_node = (function() {
var memo;
console.log("memo: " + memo);
console.log("create_node")
function f() {
var value;
if (memo) {
value = memo.cloneNode();
console.log("clone node");
console.log(value);
} else {
var value = document.createElement("div");
value.innerHTML = "hello";
console.log("new node");
console.log("value: " + value);
memo = value;
}
return value;
}
return f;
})();
var collection = [];
for (var i = 0; i < 10; i++) {
collection.push(create_node());
};
// Display results
for (var i = 0; i < 10; i++) {
console.log(i + ". " + collection[i]);
}
}
main();
Since functions in javascript are an object, you can just use that function to memoize the value. I think it would make more sense in fib example, but here is your original post.
function main() {
// memoizing function
function create_node() {
var value;
// read from memo on function object
if (create_node.memo) {
value = create_node.memo.cloneNode();
value.innerHTML = 'cloned';
console.log("clone node");
console.log(value);
} else {
var value = document.createElement("div");
value.innerHTML = "hello";
console.log("new node");
console.log("value: " + value);
// retain memo on the function object
create_node.memo = value;
}
return value;
}
var collection = [];
for (var i = 0; i < 10; i++) {
collection.push(create_node());
};
// Display results
for (var i = 0; i < 10; i++) {
console.log(i + ". " + collection[i]);
document.getElementById('container').appendChild(collection[i]);
}
}
main();
<div id="container"></div>
Your actual memoized function is f. The (function(){ ... })() IIFE wrapping merely provides a an additional closure-layer to hide the variable memo so that it is visible only to f.
To repeat that: the (function(){...})() expression is not your memoized function. It is wrapping that restricts visibility of an inner variable and ultimately returns your memoized function f, which is defined inside of it. If you were okay with exposing memo to other code in main and not restrict its visibility to the memoized function only, you could eliminate the IIFE wrapping entirely and simply rename f to create_node:
function main() {
var memo;
function create_node() {
var value;
if (memo) { value = memo.cloneNode(); }
else {
var value = document.createElement("div");
value.innerHTML = "hello";
memo = value;
}
return value;
}
// use `create_node` as originally done
// NOTE that other code can manipulate `memo` now, though!
}
main();
If you like, you can supply the closure wrapping via a function declaration instead of IIFE:
function createMemoizedFunc() {
var memo;
function f() {
var value;
if (memo) { value = memo.cloneNode(); }
else {
var value = document.createElement("div");
value.innerHTML = "hello";
memo = value;
}
return value;
}
return f;
}
var create_node = createMemoizedFunc();
I have the following code in a separate file that is referenced with tags
function _TEST()
{
var val;
this.get = function(x)
{
return val;
}
this.prop = 'testing';
this.set = function(x)
{
val = x
return val;
}
this.exp = function(x)
{
function meth(x)
{
return 'I am a private '+x;
}
return meth(x);
}
}
Now in the head section of the main page I have
var tst = new _TEST();
window.onload = function()
{
tst.set('Hello')
alert(tst.get());
var tst2 = Object.create(_TEST.prototype);
tst2.prop = "testing"; // the only property that shows up for tst2 below
var str = '';
for(var x in tst)
{
str += x+" : "+tst[x]+"\n";
}
str += "\n\ntst2:\n"
for(var x in tst2)
{
str += x+" : "+tst2[x]+"\n";
}
alert(str)
}
The output from the call to alert is:
get : function (x) {
return val;
}
prop : testing
set : function (x) {
val = x;
return val;
}
exp : function (x) {
function meth(x) {
return "I am a private " + x;
}
return meth(x);
}
tst2:
prop : testing
As I understand it Object.create is suppose to create an object instande that inherits from the prototype.
but tst2 has none of those. What am I doing wrong here?
This is being tested in Firefox 12.0 on Mac OSX and I am not sure what version of javascript it uses. I am
Using O'Reillies Javascript: the Definitive Guide (rhino book) to increase my knowledge of objects and related
code
Edit:
I figured it out:
it works with
var tst2 = Object.create(tst);
Your code has not added any properties to the _TEST.prototype. The _TEST function adds properties directly to each instance created when a new _TEST() call is made. That has nothing to do with the prototype.
I'm trying to assign the variable strSel in the function outputSelected to the variable TestVar in the function testResults. What's the best way to achieve this?
function getSelected(opt) {
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if ((opt[intLoop].selected) || (opt[intLoop].checked)) {
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function outputSelected(opt) {
var sel = getSelected(opt);
var strSel = "";
for (var item in sel)
strSel += sel[item].value + ",";
window.document.title = strSel;
}
function testResults (form) {
var TestVar = // Want to pass strSel here.
window.document.title=(TestVar);
}
Just use a global variable :-
then set this variable in one function and you can use this variable value in another function.
var myvar;// declare global variable
function outputSelected(opt) {
var sel = getSelected(opt);
var strSel = "";
for (var item in sel)
strSel += sel[item].value + ",";
// set the var:-
myvar=strSel ;
window.document.title=(strSel); <----- result
}
function testResults (form) {
var TestVar= myvar;
//alert (TestVar + "\n" + TestVar1 + "\n" + TestVar2 + "\n" + TestVar3 + "\n" + TestVar4 + "\n" + TestVar5);
window.document.title=(TestVar);
}
You can use a global variable or return the value in the function outputSelected() and call and assign it in your other function.
You could return the value from outputSelected and then pass it into your testResults method:
Changes:
function outputSelected(opt) {
// current code
return strSel;
}
function testResults(form) {
var TestVar = form;
window.document.title = TestVar;
}
And call the methods like so:
testResults(outputSelected(opt));